如何从CBPeripheral和CBCenter获取Mac地址

问题描述 投票:0回答:2

我需要从 CBPeripheral 和 CBCenter 的输入连接和传出连接中获取目标 mac 地址。标识符没有在其中定义。 外观已从 iOS 7 中删除。还有其他方法吗?

https://developer.apple.com/library/prerelease/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/index.html

ios core-bluetooth btle
2个回答
18
投票

您无法获取

CBPeripheral
的 MAC 地址,但可以获取
identifier
属性,这是 iOS 根据 MAC 和其他信息计算的 UUID。

该值可以安全地存储并用于将来在该特定 iOS 设备上识别相同的外围设备。

不能在其他iOS设备上使用来识别同一外设。


-3
投票

您可以在 iOS 12 中毫无问题地访问 MAC 地址。 要获取 mac 地址,您必须按照以下步骤操作。

  1. 将BLE设备接收到的Data解析为String。
extension Data{
func hexEncodedString() -> String {
        let hexDigits = Array("0123456789abcdef".utf16)
        var hexChars = [UTF16.CodeUnit]()
        hexChars.reserveCapacity(count * 2)

        for byte in self {
            let (index1, index2) = Int(byte).quotientAndRemainder(dividingBy: 16)
            hexChars.insert(hexDigits[index2], at: 0)
            hexChars.insert(hexDigits[index1], at: 0)
        }
        return String(utf16CodeUnits: hexChars, count: hexChars.count)
    }
}

  1. 在地址中添加分隔符“:”。
extension String {
    func separate(every stride: Int = 4, with separator: Character = " ") -> String {
        return String(enumerated().map { $0 > 0 && $0 % stride == 0 ? [separator, $1] : [$1]}.joined())
    }
}
  1. 在 didReadValueForCharacteristic(characteristic: CBCharacteristic) 中,您可以使用前面的 2 个函数来获取 mac 地址。
func didReadValueForCharacteristic(_ characteristic: CBCharacteristic) {
if characteristic.uuid == BleDeviceProfile.MAC_ADDRESS, let mac_address = characteristic.value?.hexEncodedString().uppercased(){
            let macAddress = mac_address.separate(every: 2, with: ":")
            print("MAC_ADDRESS: \(macAddress)")
        }
}
  1. 享受您的Mac地址: “MAC_地址:00:0A:57:4E:86:F2”
© www.soinside.com 2019 - 2024. All rights reserved.