在 swift 中将 CBUUID 转换为 NSNumber

Convert CBUUID to NSNumber in swift

如何将 CBUUID 转换为 UINT16?

我想获取广告数据中的设备信息为UINT16。

我遇到了错误

无法将类型 'CBUUID' (0x1d2715e68) 的值转换为 'NSNumber' (0x1d25c9db0)。 2019-12-04 14:17:18.731697-0500 ProjectName[717:125723] 无法将类型 'CBUUID' (0x1d2715e68) 的值转换为 'NSNumber' (0x1d25c9db0).

我在终端的广告数据

[
"kCBAdvDataTxPowerLevel": 0,
"kCBAdvDataIsConnectable": 1,
"kCBAdvDataTimestamp": 597179838.727399,
"kCBAdvDataServiceUUIDs": <__NSArrayM 0x281252e20>( 22043200-9530-4EA8-9D21-04146852E51F ) ,
"kCBAdvDataServiceData": { "Device Information" = {长度 = 6,字节 = 0x010000020004}; },
"kCBAdvDataLocalName": base0
]

我已经用粗体标出了我需要的信息。

我下面有下面的代码。

    public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

        guard peripheral.state != .connected else {
            return
        }


        let advertisementDataService = advertisementData[CBAdvertisementDataServiceDataKey]
        let deviceInformation = advertisementDataService as! Dictionary<UInt16,AnyObject>
}

谢谢!!!

根据[文档[(https://developer.apple.com/documentation/corebluetooth/cbadvertisementdataservicedatakey),与CBAdvertisementDataServiceDataKey关联的字典是<CBUUID,Data>类型。检索到字典后,您可以使用适当的 CBUUID 实例(0x180A 是设备信息服务)对其进行下标。

public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    guard peripheral.state != .connected else {
        return
    }


    if let deviceInformation = advertisementData[CBAdvertisementDataServiceDataKey] as? Dictionary<CBUUID,Data>, 
       let data = deviceInformation[CBUUID(string:"0x180A")] {
        // Do something with the data
    }
}