A High-Level Look at NSURLSession

Though Apple introduced NSURLSession in 2013, NSURLConnection has served as such a strong networking infrastructure that there really hasn’t been a need to update it. With the upcoming release of watchOS 2 and iOS 9 in September, refreshing Personal Capital’s tech stacks seem appropriate so we can take full advantage of Apple’s latest technology offerings.

The NSURLSession API comprises of the same components as NSURLConnection (NSURLRequest, NSURLResponse, NSHTTPCookieStorage, NSURLCache and NSURLProtocol) but replaces NSURLConnection with NSURLSession, NSURLSessionConfiguration, and NSURLSessionTask.


NSURLSession: divide and conquer

NSURLSession introduces the concept of configuring cache, cookie, credential, and protocol policies into sessions instead of sharing these policies throughout the app. This allows you to separate network tasks into appropriate sessions as needed so changes to protocols, credentials, cookie storage, or cache storage can be localized to only the tasks in that session. This is done by initializing an NSURLSession with an NSURLSessionConfiguration. After initialization, you cannot change a session’s configuration. If you feel a need to do so, this probably means the network request or task belongs in a different session. If needed, you can override HTTP header values set in the HTTPAdditionalHeaders property of a session’s configuration by setting them in the NSURLRequest.


NSURLSessionConfiguration: persist/share, private, and background

NSURLSessionConfiguration has 3 types of constructors.
+ defaultSessionConfiguration returns the default configuration and defaults to using the same shared cache, cookie, and credentials storage that are familiar with NSURLConnection.
+ ephemeralSessionConfiguration returns a configuration that uses no persistent storage for cache, cookie, and credentials. This configuration would be used if you wanted to create a feature similar to private browsing.
+ backgroundSessionConfigurationWithIdentifier: returns a configuration that allows HTTP and HTTPS uploads and downloads while the app is in the background. If an upload or download is interrupted because the app is terminated by the system, the upload or download can be resumed by creating a new NSURLSessionConfiguration with the same identifier that was used for the interrupted configuration and passing that to a new NSURLSession. Interrupted tasks cannot be resumed if the app was terminated by the user.


NSURLSessionTask: reminds me of NSURLConnection with a completionHandler … and background support!

NSURLSessionTask is analogous to NSURLConnection because it’s the base class for handling requests for data as well as the uploading and downloading of files. NSURLSessionTask consists of three different subclasses.

  • NSURLSessionDataTask is used for making HTTP and HTTPS requests and return the server’s response as NSData in memory. An NSURLSessionTask can be constructed by providing an NSURL object or an NSURLRequest. These tasks are only supported in default and ephemeral sessions.
  • NSURLSessionUploadTask is a subclass of NSURLSessionDataTask but these tasks provide an easier way to upload content. For example, you can create an NSURLSessionUploadTask by passing an NSURLRequest with either NSData representing the body data of the request or an NSURL object for the URL of the file to upload. These tasks are allowed in background sessions and provide callbacks to the session’s delegate as data is uploading. Since these tasks are allowed in background sessions, you can technically create an NSURLSessionUploadTask (pass nil for the body data) instead of an NSURLSessionDataTask if you really require the task to continue in the background.
  • NSURLSessionDownloadTask is a task that directly writes the server’s response data to a temporary file. After completion, the app needs to move the temporary file to an appropriate place. These tasks can run in any type of session.

Instead of allocating an NSURLSessionTask on it’s own, tasks are instantiated by an NSURLSession object. An NSURLSessionTask can be constructed with and without a completionHandler. If a completionHandler is provided, it will be executed after the request is completed on the delegate queue. For NSURLSessionDataTask and NSURLSessionUploadTask tasks, the completionHandler will return the NSData and NSURLResponse object returned by the server or an NSError object if an error occurred. The completionHandler for an NSURLSessionDownloadTask task returns the location of the downloaded file as an NSURL object, the NSURLResponse from the server, or an NSError object if an error occurred.


Delegates: why to not construct with a completionHandler

You may be wondering why you would ever create an NSURLSessionTask without a completionHandler. If you require finer control over the progress of an NSURLSessionTask, you need to provide a delegate. If you provide a delegate and also provide a completionHandler, you will notice that none of the callbacks related to progress are called. (You will still get URLSession:task:didReceiveChallenge:completionHandler:.) If you want to receive all of the callbacks, you need to construct your task without a completionHandler. The combination of NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, and NSURLDataDownloadDelegate cover the delegate methods that NSURLConnectionDelegate and NSURLConnectionDataDelegate provided for NSURLConnection. Each of these delegates are well documented so there’s no need to go over them in this article. One thing to note, though, is that both NSURLSessionDelegate and NSURLSessionTaskDelegate provide callbacks for authentication challenges. The callback for NSURLSessionDelegate handles authentication challenges at the connection level (NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate, and NSURLAuthenticationMethodServerTrust). If URLSession:didReceiveChallenge:completionHandler: is not implemented at the session level, the callback at the task level is called. URLSession:task:didReceiveChallenge:completionHandler: will additionally handle authentication challenges at the request level.


Further reading

All of the information mentioned in this article can be further studied in the NSURLSession Class Reference from the iOS Developer Library (https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/).

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>