User
User

Reputation: 24731

Printing NSData in Swift?

How do you output the value of NSData in Swift? Is it NSLog, print or println?

It seems I can just print the address of the object, and not the actual contents of it.

Thank-you

Upvotes: 25

Views: 31529

Answers (3)

User
User

Reputation: 24731

So after trying a number of recommendations around the site, this is what actually ended up working for me.

Swift 3

let string1 = String(data: jsonData, encoding: String.Encoding.utf8) ?? "Data could not be printed"
print(string1)

Swift 1

let string1 = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
println(string1)

Upvotes: 55

Cargowire
Cargowire

Reputation: 1462

If you want just the bytes (and don't know, or there isn't an appropriate string encoding) you can still use NSLog in swift:

NSLog("%@", NSData(bytes: [0x1b], length:1))

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Try NSString

let theString:NSString = NSString(data: someNSData, encoding: NSASCIIStringEncoding)
println(theString)

Reference

convenience init(data: NSData, encoding: UInt)

Upvotes: 4

Related Questions