我正在扫描蓝牙设备。我想将它们记录在字符串数组中。我希望能够保存它们,但出现以下错误:
无法将类型“ 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
}
}
任何关于将它们作为字符串获取的想法,因此我可以将它们存储在数组中。如果您有更好的方法,请告诉我。谢谢!
答案 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命名约定,即变量名(uidCountNumber
,uidCount
和lastUID
的lowerCamelCase)。
答案 2 :(得分:2)
Apple提供了用于获取字符串的API:
https://developer.apple.com/documentation/corebluetooth/cbuuid/1518742-uuidstring
var uuidString: String { get }