converting String to Data in swift 3.0
Asked Answered
E

1

34

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?

Ernestoernestus answered 10/10, 2016 at 19:39 Comment(5)
There's nothing wrong. By the way, .utf8 is sufficient.Shirberg
See for example #39075543, or just print(newData as NSData).Facilitation
The reason it is printing 12 bytes is it takes 12 bytes to store 12 characters in UTF8 (1 byte per character for ASCII characters).Thorncombe
@MartinR as NSData is pretty smart.Shirberg
I assume that your code should works fine...Federation
C
12

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

Cutlet answered 10/10, 2016 at 20:2 Comment(5)
So it sounds like self.peripheral?.writeValue(newData, for: positionCharacteristic, type: CBCharacteristicWriteType.withResponse) should work then. I'm not sure why I'm not seeing anything in my terminal. I have data going the other way.Ernestoernestus
The body of your function can be replaced with return self.map{ String(format:"%02x", $0) }.joined(separator:separator)Shirberg
Not sure I understand the failure @lusher00. Sounds like your question is more than "why doesn't it show me the bytes themselves instead of the byte count?" What more are you expecting to see where? Which terminal are you referring to?Cutlet
Thanks @vadian, updated. I think I inlined it because I was trying to avoid any intermediate array of nibble printed strings. But I never really tested to see if it wasn't smarter than that. And I really had no justification for early optimizing :)Cutlet
I thought seeing the byte count was my failure but that doesn't appear to be the case anymore. I guess that really was all I asked in my original question so I'm just going to mark this as answered and move on. Thank you.Ernestoernestus

© 2022 - 2024 — McMap. All rights reserved.