【问题标题】:How to get Mac Address From CBPeripheral And CBCenter如何从 CBPeripheral 和 CBCenter 获取 Mac 地址
【发布时间】:2016-01-13 17:59:38
【问题描述】:

我需要从 CBPeripheral 和 CBCenter 的输入连接和传出连接中获取目标 mac 地址。标识符未在其中定义。 外观已从 iOS 7 中删除。还有其他方法吗?

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

【问题讨论】:

  • 外设的硬件MAC地址不可用。
  • 谢谢,CBCenter 怎么样?
  • 不,没有可用的 MAC 地址。您可以获取标识符,但这是根据底层 MAC 计算得出的 UUID
  • 有唯一的名称或地址吗?我想将它存储在数据库中,但在断开连接并重新连接时,我想要再次使用相同的地址。
  • 没错。但标识符不再存在。

标签: ios core-bluetooth btle


【解决方案1】:

您无法获取 CBPeripheral 的 MAC 地址,但您可以获得 identifier 属性,这是 iOS 从 MAC 以及其他信息中计算出来的 UUID。

此值可以安全地存储并用于在未来识别此特定 iOS 设备上的相同外围设备。

它不能在另一个 iOS 设备上使用来识别相同的外围设备。

【讨论】:

  • 我没有找到任何关于“iOS从MAC计算”的话的证据,也许你可以分享链接来证明它?我已经检查过,不同的 iPhone 显示同一 BLE 设备的不同 UUID。也许这可以识别当前iOs设备的设备,但不是一般的。
  • 我应该澄清我的答案;该标识符只能在同一设备上使用。它不能跨设备使用
  • 但是在 android 你可以为我的 BLE 设备获取 MacAddress
  • 是的。但在 iOS 上你不能。
【解决方案2】:

您可以在 iOS 12 中毫无问题地访问 MAC 地址。 要获取 mac 地址,您必须按照以下步骤操作。

  1. 将BLE设备接收到的Data解析为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. 在地址中添加分隔符“:”。
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. 在didReadValueForCharacteristic(characteristic: CBCharacteritic)中可以使用前面2个函数来获取mac地址。
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. 享受你的mac地址: "MAC_ADDRESS: 00:0A:57:4E:86:F2"

【讨论】:

  • 非常感谢出色的解决方法你能解​​释一下这个 BleDeviceProfile.MAC_ADDRESS 到底是什么
  • 在我的示例中,BLE 设备的 MAC ADDRESS 位于特征内
  • 在此示例中,您似乎有意将 MAC 暴露为特征。是否所有 BLE 设备都将其 mac 暴露为特征?
猜你喜欢
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
相关资源
最近更新 更多