在Swift

时间:2018-11-07 14:41:31

标签: ios swift core-bluetooth

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

无法将类型“ 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

    }
}

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

3 个答案:

答案 0 :(得分:3)

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语句或可选链接

答案 1 :(得分:3)

问题在于服务UUID的类型为CBUUID,因此您应强制转换为[CBUUID]而不是NSArray<String>。顺便说一句,从CB...Key检索值时,最好使用advertisementData常量而不是String常量。

一旦您拥有单个CBUUID实例,就可以使用uuidString将其转换为String并将其显示在UILabel上。

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

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

        print("peripheral Name: \(peripheralName)")
        guard let uniqueIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID], let uniqueID = uniqueIDs.first else { return }

        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.uuidString

    }
}

与您的问题无关,但您还应遵守Swift命名约定,即变量名(uidCountNumberuidCountlastUID的lowerCamelCase)。

答案 2 :(得分:2)

Apple提供了用于获取字符串的API:

https://developer.apple.com/documentation/corebluetooth/cbuuid/1518742-uuidstring

var uuidString: String { get }