iOS Dev Nugget 144 NSURLSession instead of NSURLConnection


Need to run a code review on your codebase? Hire me

NSURLSession was introduced along with iOS 7 as a replacement for NSURLConnection. Session 705 "What’s New in Foundation Networking" in WWDC 2013 talks in great detail about NSURLSession and the advantages of it including access to configuration on a per session basis. Here's a common example of how to use NSURLSession which you can immediately replace NSURLConnection with. Let's say you want to perform a GET on a URL and retrieve the response:

var conf = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: conf)

let urlString = ""
var task = session.downloadTaskWithURL(NSURL(string: urlString)!) {url, response, error in
    dispatch_async(dispatch_get_main_queue()) {
        if let error = error {
            //Handle error
            println("error: \(error)")
        } else {
            var stringContents = NSString(data: NSData(contentsOfURL: url)!, encoding: NSUTF8StringEncoding)
            println("results: \(stringContents)")

You create a NSURLSession instance that can be shared across request. For each request, you create a new task. You always resume() a task to run it.

The NSURLSession instance is configured via a NSURLSessionConfiguration instance. For example, if you want to restrict requests for this session to not use cellular connectivity, you can do:

conf.allowsCellularAccess = false

Or if the requests are for a JSON API that uses Basic Authentication:

let username = "some user name"
let password = "some password"
let userPasswordString = "#{username}:#{password}"
let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let authString = "Basic \(base64EncodedCredential)"
conf.HTTPAdditionalHeaders = ["Accept": "application/json", "Authorization": authString]

These configurations can all be made on a per session basis.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues