3

I have app what working with BLE device. I have characteristic value, but I can't convert it to string. For example,

value = <aa640400 0000001e 0f>

How convert it to string?

3 Answers3

1
let dd = getCharacteristic.value!;

print(String(data: dd, encoding: String.Encoding.ascii)!);
Bugs
  • 4,491
  • 9
  • 32
  • 41
Deepak Tagadiya
  • 2,187
  • 15
  • 28
0

I was using the answer from sandy above and condensed it to

let data = (characteristic.value)!    
let nsdataStr = NSData.init(data: (characteristic.value)!)
print("Raw: \(nsdaraStr)")

All I wanted to do was to get the raw value (in hex) from the BLE peripheral (HR monitor in this case). The output of the above gives me:

// This is the Decimal HRArray:[22, 64, 90, 3] 
Raw: {length = 4, bytes = 0x16404e03}

This code below basically just removes the white space

let str = nsdataStr.description.trimmingCharacters(in:charSet).replacingOccurrences(of: " ", with: "")

making it

Raw: {length=4, bytes=0x16404e03}

which I didn't need.

app4g
  • 670
  • 4
  • 24
  • Please use https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift instead. Else, this will be obsolete in future version (iOS13 changed the Data description: https://stackoverflow.com/questions/57839723/does-ios-13-has-new-way-of-getting-device-notification-token). – Larme Oct 09 '20 at 09:13
-1

Follow below code:

let data = (characteristic?.value)!

print(data) //-> It will be of type Data we need to convert Data to String

let charSet = CharacterSet(charactersIn: "<>")

let nsdataStr = NSData.init(data: (characteristic?.value)!)

let str = nsdataStr.description.trimmingCharacters(in:charSet).replacingOccurrences(of: " ", with: "")

print(str) // you will get String or Hex value (if its Hex need one more conversion)
Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59
sandy
  • 1
  • 1