0

I'm trying to get data from spesific bluetooth device in JSON format. As I understood CoreBluetooth in didUpdateValueFor CBCharacteristic delegate send 20 bytes massage and you can work with it. The problem is if this 20 bytes massage has Cyrillic symbols, didUpdateValueFor CBCharacteristic delegate don't send me this 20 bytes and at the end I have not valid JSON. Example:

{"Rows":[ 
     {"num":0,"id":1,"pid":0,"type":0,"name":"Папка1"},
     {"num":1,"id":2,"pid":0,"type":0,"name":"Group2"},
     {"num":2,"id":4,"pid":1,,"id":5,"pid":2,"type":1,"name":"Group2запись"}
]}

As you can see, in this json after {"num":2,"id":4,"pid":1, I had 20 bytes with Cyrillic.

Device sents data in UTF8

I convert this data to string as below

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let readValue = myCharacteristic.value ?? Data()
jsonString1 = String(data: readValue, encoding: String.Encoding.utf8) ?? ""
massageFromDevice = massageFromDevice + jsonString1

How can I solve it?

Mike
  • 11
  • 1
  • 5
  • You need to use the appropriate string encoding when you convert the data back into a string. How is the data being sent? Is it a UTF16 string? You may also need to concatenation the data from multiple packets before attempting to convert it to a string as a character sequence may span transfers. You should edit your question to show the relevant code; how are you processing the received bytes? – Paulw11 Sep 28 '18 at 11:47
  • 1
    You try to decode only 20bytes, but your response from BLE is larger, so you'll have to append the data and when the ble is done writing then you decode the content. You can also check this awesome lib for BLE: https://github.com/Polidea/RxBluetoothKit – danypata Sep 28 '18 at 12:42

0 Answers0