NyoSeint Lay NyoSeint Lay - 1 year ago 481
iOS Question

CBCharacteristic value in swift3

I am beginner in swift development. I was working on BLE based application.
Today I updated Xcode 8, iOS 10 and convert my code to swift3. Then some of my syntax are need to convert. After fixing this , I found one issue on CBCharacteristic.


Inside didUpdateValueforCharacteristic , I can get updated CBCharacteristic object.
If I print out whole object, it show correctly. -> value = <3a02>
When I retrieved value from CBCharacteristic , characteristic.value -> 2bytes (size of this value)

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)
if (characteristic.uuid.description == LED_WAVELENGTH_CHARACTERISTIC_UUID)
print("Characteristic - \(characteristic)")
print("Data for characteristic Wavelength - \ (characteristic.value)")

Log Result :

Characteristic - <CBCharacteristic: 0x1742a50a0, UUID = 2C14, properties = 0xE, value = <3a02>, notifying = NO>
Data for characteristic Wavelength - Optional(2 bytes)

PS : This code is completely working fine on previous version.

Thanks for attention and hope someone can help me to fix this issue.

Answer Source

It seems that you have been relying on the description of NSData returning a string of the form <xxxx> in order to retrieve the value of your data. This is fragile, as you have found, since the description function is only meant for debugging and can change without warning.

The correct approach is to access the byte array that is wrapped in the Data object. This has been made a little bit more tricky, since Swift 2 would let you copy UInt8 values into a single element UInt16 array. Swift 3 won't let you do this, so you need to do the math yourself.

var wavelength: UInt16?
if let data = characteristic.value {
    var bytes = Array(repeating: 0 as UInt8, count:someData.count/MemoryLayout<UInt8>.size)

    data.copyBytes(to: &bytes, count:data.count)
    let data16 = bytes.map { UInt16($0) }
    wavelength = 256 * data16[1] + data16[0]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download