1

I get this data from BLE, but is crashes on certain values (I think when data is float )

function to get data :

  func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {

         print(characteristic); // prints a value always
         if characteristic.UUID == UUID_CHAR {

            if ( characteristic.value == nil)
            {return; }

             //***crash is here :
             let str:NSString = NSString(data: characteristic.value!, encoding: NSUTF8StringEncoding)!
            print ("got::",str);  

This will crash when the characteristic is :

<CBCharacteristic: 0x157685860, UUID = FFE1, properties = 0x16, value = <00ff00>, notifying = YES>

and not when its this : (value field here is 00 )

<CBCharacteristic: 0x157685860, UUID = FFE1, properties = 0x16, value = <00>, notifying = YES>

I have tried wrapping it with if let , which did not worked.

ERROR: unexpectedly found nil while unwrapping an Optional value

How would you cast the value to string, knowing it could be a float or integer ?

Curnelious
  • 1
  • 16
  • 76
  • 150
  • Not a duplicate at all, and does not have any connection to this question. I already wrote that I did tried to wrap the value . – Curnelious Aug 07 '16 at 14:57
  • 1
    `00ff00` is not a valid UTF-8 sequence, and therefore `NSString(data: characteristic.value!, encoding: NSUTF8StringEncoding)` returns `nil` and unwrapping that crashes. – `00ff00` also does not look like a floating point number to me (which usually would be 4 or 8 bytes). See http://stackoverflow.com/a/27949099/1187415 for an example how to access the bytes from the data. – Martin R Aug 07 '16 at 15:03
  • @MartinR Thanks I have tried that solution, it did not work, the thing is that you don't know what value you get, it might be a string, or a float, or an int , is there one way to do this right ? I can not find reliable solution. – Curnelious Aug 07 '16 at 17:25
  • Without any information you can only *guess* what `00 FF 00` represents. I am not an expert for Bluetooth communication, but I would assume that it is *documented* somewhere how the data is represented. – Martin R Aug 07 '16 at 17:40
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Aug 10 '16 at 05:48

1 Answers1

2

Don't need to cast to NSString, Then you don't have to forcefully unwrap the result. Try this:

let str = NSString(data: characteristic.value!, encoding: NSUTF8StringEncoding)

Now if the value is not a valid UTF-8 Sequence, You won't get a crash

Irfan
  • 5,070
  • 1
  • 28
  • 32