How to get Mac Address From CBPeripheral And CBCenter

时光毁灭记忆、已成空白 提交于 2019-11-28 04:22:30

问题


I need to take target mac address from input connection and outgoing connection from CBPeripheral And CBCenter. identifier dose not define in them. look was remove from iOS 7. Is there any other way?

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


回答1:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/33145798/how-to-get-mac-address-from-cbperipheral-and-cbcenter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!