2

I have been unable to convert CBCharacteristic's value property which is of type NSData to NSString. I tried the usual initWithData:encoding: method of NSString as given below. But it returns nil.

NSString *str = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);

I am able to see the string value on console when I do NSLog on value directly.

NSLog(@"characteristic.value: %@", characteristic.value);

Can aanybody give any idea on how to get the string value out of characteristic.value?

saikamesh
  • 4,569
  • 11
  • 53
  • 93
  • Not all binary data (`NSData`) have a meaning in UTF8 String. You'll probably get nil if you convert `[[NSString alloc] initWithData:UIImagePNGRepresentation(someUIImage) encoding:NSUTF8StringEncoding];`. – Larme Oct 25 '17 at 08:14
  • @Larme: Yes, correct. But in this case it is a known characteristics which has a hexadecimal no as string(uuid format). I am able to see the value of it when I print the data. NSLog(@"characteristic.value: %@", characteristic.value); – saikamesh Oct 25 '17 at 08:57
  • Show us the value and the result you want then. – Larme Oct 25 '17 at 08:58
  • It prints. value: <11122334 45566778 899aabbc cddeeff0 00>. This is the default value assigned to the characteristics. I have hardwired this value in my code. If the characteristics has this value then I will have to do some calculation and change the value of it to something else. – saikamesh Oct 25 '17 at 09:01
  • 1
    If you just want to check that it's equal, you can use https://stackoverflow.com/questions/7317860/converting-hex-nsstring-to-nsdata to convert the `@"11122334 45566778 899aabbc cddeeff0 00"` as NSString into NSData and do a `isEqual:`. – Larme Oct 25 '17 at 09:04
  • Thanks Larm for the easy solution. It works fine. – saikamesh Oct 25 '17 at 16:02
  • If the value is fix, it's maybe faster to use a Byte array instead of all that conversion from string. – Larme Oct 25 '17 at 16:05
  • Any idea why I am not able to read the string value from the characteristic as shown below. NSString *str = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding]; NSLog(@"%@", str); – saikamesh Oct 25 '17 at 16:15
  • Because it's not a valid UTF8 data I guess? – Larme Oct 25 '17 at 16:16

1 Answers1

0
  • You need to know what means the NSData. Could be a String, struct, uint32, etc. See here: core-bluetooth-get-all-features-description

  • Is BLevel for battery level? You need to do reverse engineering or read the doc (BLE doc if it's a "known" one, or device doc)

Bhavin Thummar
  • 181
  • 10
  • 7