我正在扫描蓝牙设备。我想将它们记录在字符串数组中。我希望能够保存它们,但出现以下错误:

无法将类型'CBUUID'(0x1f2760918)的值强制转换为'NSString'(0x1f26a42d0)。

CoreBT [9728:3053605]无法将类型'CBUUID'(0x1f2760918)的值强制转换为'NSString'(0x1f26a42d0)。

我下面有以下代码。没有对数组的引用,因为我什至无法将其获取为字符串。

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

    if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {


        print("peripheral Name: \(peripheralName)")

        let uniqueID = (advertisementData["kCBAdvDataServiceUUIDs"] as! NSArray).firstObject! as! String
        // The above line produces an error
        //Removing as! String will work prevent error but still cannot get from "any" to "string"

        let x = advertisementData
        print("x: \(x)")
        let y = advertisementData["kCBAdvDataServiceUUIDs"]
        print("y: \(y)")

        print("uniqueID: \(uniqueID)")
        self.UIDCountNumber = UIDCountNumber + 1
        self.UID_Count.text = String(self.UIDCountNumber)//label counting devices


        self.last_UID.text = uniqueID as? String //Label is not changing

    }
}

关于将它们作为字符串获取的任何想法,这样我就可以将它们存储在数组中。如果您有更好的方法,请告诉我。谢谢!

最佳答案

线

let uniqueID = (advertisementData["kCBAdvDataServiceUUIDs"] as! NSArray).firstObject! as! String

由于UUID不是String类型而是完全不相关的CBUUID类型,因此会导致崩溃。您可以像这样从CBUUID中提取UUID字符串
guard let uuids = advertisementData["kCBAdvDataServiceUUIDs"] as? [CBUUID] else { return }
guard let uniqueID = uuids.first?.uuidString else { return }

另外,放弃强制转换运算符-as!。这是一个非常糟糕的做法。使用guard语句或可选的链接

关于ios - 在Swift中将CBUUID转换为字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53191695/

10-12 02:05