Reputation: 678
I'm trying to convert a string to a data type. I thought this was all I needed but if I try to print it it just prints "12 bytes"
let tString = "Hello World!"
if let newData = tString.data(using: String.Encoding.utf8){
print(newData)
self.peripheral?.writeValue(newData, for: positionCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
What am I doing wrong?
Upvotes: 34
Views: 26588
Reputation: 22252
You are not doing anything wrong. That's just how Data currently does its debug printout. It has changed over time. It has at times printed more like NSData. Depending on the debug print format is pretty fragile, I think it's better to just own it more directly. I have found the following pretty useful:
extension Data {
func hex(separator:String = "") -> String {
return (self.map { String(format: "%02X", $0) }).joined(separator: separator)
}
}
This allows me to replace your simple print(newData)
with something like
print(newData.hex())
or
print(newData.hex(separator:"."))
if my eyes need help parsing the bytes
aside, I do quite a bit of BLE stuff myself, and have worked up a number of other useful Data extensions for BLE stuff
Upvotes: 12