How to get Mac Address From CBPeripheral And CBCenter

巧了我就是萌 提交于 2019-11-29 11:00:35

You can't get the MAC address for a CBPeripheral but you can get the identifier property, which is a UUID that iOS computes from the MAC amongst other information.

This value can be safely stored and used to identify the same peripheral in the future on this particular iOS device.

It cannot be used on another iOS device to identify the same peripheral.

You can access to the MAC ADDRESS without problem in iOS 12. To get the mac address you have to follow the next steps.

  1. Parse the Data received by the BLE device to 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. Add a separator ":" to the address.
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. In didReadValueForCharacteristic( characteristic: CBCharacteritic) you can use the previous 2 functions to get the mac address.
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. enjoy your mac address: "MAC_ADDRESS: 00:0A:57:4E:86:F2"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!