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?

James Zaghini
  • 3,895
  • 4
  • 45
  • 61
lusher00
  • 678
  • 1
  • 7
  • 18

1 Answers1

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

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • 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. – lusher00 Oct 10 '16 at 20:08
  • 1
    The body of your function can be replaced with `return self.map{ String(format:"%02x", $0) }.joined(separator:separator)` – vadian Oct 10 '16 at 20:11
  • 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? – Travis Griggs Oct 10 '16 at 20:14
  • 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 :) – Travis Griggs Oct 10 '16 at 20:20
  • 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. – lusher00 Oct 10 '16 at 20:21