How to get Mac Address From CBPeripheral And CBCenter

后端 未结 2 1158
情话喂你
情话喂你 2020-12-18 00:55

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

2条回答
  •  [愿得一人]
    2020-12-18 01:21

    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"

提交回复
热议问题