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.
Issue
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.
Now, you can use
String(bytes: characteristic.value!, encoding: String.Encoding.utf8)
, to get the string value of the characteristic.It seems that you have been relying on the
description
ofNSData
returning a string of the form<xxxx>
in order to retrieve the value of your data. This is fragile, as you have found, since thedescription
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.