qwdtimes2 qwdtimes2 - 3 months ago 10x
Swift Question

Base64 is a NSString and not a String

I have troubles to get the String from a NSURLSession.
The code below connects to my server and it should return a Base64 String.

All I get is a NSString.
At the end of this post is an output example.
Why does it add "optional" in front of the String? And how do I save this String to a variable? I need the String for decoding the Base64.

let url = NSURL(string: "url here")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
print(NSString(data: data!, encoding: NSUTF8StringEncoding))





The initializer init?(data:encoding:) returns an optional NSString, because it's (very) possible for the given data to not represent a valid string encoded with the provided encoding type. In this case, rather than crashing, throwing errors, or returning strings like "error", it returns nil, which the Swift compiler demands you deal with.

You can learn more about Swift's Optionals in The Swift Language Guide (Swift 2.2) - The Basics - Optionals