我需要从 CBPeripheral 和 CBCenter 的输入连接和传出连接中获取目标 mac 地址。标识符没有在其中定义。 外观已从 iOS 7 中删除。还有其他方法吗?
您无法获取
CBPeripheral
的 MAC 地址,但可以获取 identifier
属性,这是 iOS 根据 MAC 和其他信息计算的 UUID。
该值可以安全地存储并用于将来在该特定 iOS 设备上识别相同的外围设备。
不能在其他iOS设备上使用来识别同一外设。
您可以在 iOS 12 中毫无问题地访问 MAC 地址。 要获取 mac 地址,您必须按照以下步骤操作。
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)
}
}
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())
}
}
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)")
}
}