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?
UTF8View Elements Match Encoded C Strings Swift streamlines interoperation with C string APIs by letting you pass a String instance to a function as an Int8 or UInt8 pointer. When you call a C function using a String , Swift automatically creates a buffer of UTF-8 code units and passes a pointer to that buffer.
NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.
let date = Date(); let dateFormatter = DateFormatter(); Date will give us the current date and time with respect to our current time zone. For me, it's Wednesday, June 1st, 2022. dateFormatter is an instance of the DateFormatter class that allows us to operate various formatting functions on our date .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With