Get MAC address of bluetooth low energy peripheral in iOS

前端 未结 5 492
遥遥无期
遥遥无期 2020-11-28 04:05

I am currently working on an iOS application based on bluetooth low energy devices. In order to get a unique identifier to compare the peripherals got, I have to get the MAC

5条回答
  •  一向
    一向 (楼主)
    2020-11-28 04:50

    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"

提交回复
热议问题