Search code examples
swiftcore-bluetooth

Convert UUID to String representation eg: 1816 to Cycling Speed And Cadence


I'm connecting to a Cycling Speed and Cadence service via bluetooth and am saving the peripheral into an array (for tableview).

I have implemented this struct

struct BTPeripheral: Identifiable {
    let id: Int
    let name: String
    let uuid: UUID
    let desc: String
}

and am calling is as

discoveredBTDevices.append(BTPeripheral.init(
                           id: discoveredBTDevices.count, 
                           name: peripheral.name!, 
                           uuid: peripheral.identifier, 
                           desc: service.uuid.uuidstring) // trying service.uuid results in error
)

which results in this output

id: 0, 
name: "Wahoo CADENCE 1DE8", 
uuid: E98F3843-1C6A-E4DE-6EF3-76B013950007, 
desc: "1816"

The description is the string 1816 (which is the UUID of the cycle Speed & Cad service)

let serviceCyclingSpeedAndCadenceUUID             = CBUUID(string: "1816")

How can I convert the 1816 into the string "Cycling Speed and Cadence" which is what gets printed out

print(service.uuid) // this results in "cycling Speed and Cadence"

As noted above, putting service.uuid results in an error Cannot convert value of type 'CBUUID' to expected argument type 'String'


Solution

  • You can just get its description (which, IIRC, is what print will do eventually, as CBUUID conforms to CustomStringConvertible):

    service.uuid.description
    

    Or use a string interpolation:

    "\(service.uuid)"
    

    debugDescription produces the same result too, but I wouldn't use this unless this is actually for debugging.