Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting String to Data in swift 3.0

Tags:

swift

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?

like image 537
lusher00 Avatar asked Oct 10 '16 19:10

lusher00


People also ask

What is utf8 in Swift?

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.

What is NSData?

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.

How do I change the date format in Swift?

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 .


1 Answers

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

like image 83
Travis Griggs Avatar answered Oct 13 '22 01:10

Travis Griggs