Search code examples
iosswiftcore-bluetooth

Converting CBUUID to String in Swift


I am scanning for BlueTooth devices. I want to log them in an array of strings. I want to be able to save them but get the following errors:

Could not cast value of type 'CBUUID' (0x1f2760918) to 'NSString' (0x1f26a42d0).

CoreBT[9728:3053605] Could not cast value of type 'CBUUID' (0x1f2760918) to 'NSString' (0x1f26a42d0).

I have the following code below. There is no reference to an array as I can't even get it to a string.

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
        
    }
}

Any thoughts on getting these as strings so I can store them in an array?


Solution

  • The line

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

    produces a crash because the UUID is not of String type but of completely unrelated CBUUID type. You can extract UUID string from CBUUID like so

    guard let uuids = advertisementData["kCBAdvDataServiceUUIDs"] as? [CBUUID] else { return }
    guard let uniqueID = uuids.first?.uuidString else { return }
    

    Also, give up force cast operator - as!. This is a really bad practice. Use guard statements or optional chaining