wm.p1us wm.p1us - 3 months ago 49
Swift Question

Different console output data via NSData and Data (Xcode 8 beta 6, Swift 3)

I write a little snippet of usual code but found that my code don't return hex data from server with this line of code:

let currentData = try! Data(contentsOf: fullURL!)
print("currentData=", currentData)

And the output:

currentData= 24419 bytes

I tried to use Leo's comment link:


I got something hex data without spaces, and validator (http://jsonprettyprint.com) can't recognise it and returns null.


Let's try to sort out the different issues here and summarize the above comments.

The description method of Data prints only a short summary "NNN bytes", and not a hex dump as NSData did:

let o = ["foo": "bar"]
let jsonData = try! JSONSerialization.data(withJSONObject: o)

print(jsonData) // 13 bytes

You can get a hex dump by bridging to NSData (source):

print(jsonData as NSData) // <7b22666f 6f223a22 62617222 7d>

or by writing an extension method for Data (How to convert Data to hex string in swift).

But that is actually not the real problem. The JSON validator needs the JSON as a string, not as a hex dump (source):

print(String(data: jsonData, encoding: .utf8)!) // {"foo":"bar"}

And to de-serialize the JSON data into an object you would need none of the above and just call

let obj = try JSONSerialization.jsonObject(with: jsonData)