iOS NSURLSession Tutorial

NSURLSession was introduced with the release of iOS7 in 2013, Apple is positioning it as a replacement for NSURLConnection. Now, the most widely used third-party network frameworks, such as AFNetworking, SDWebImage, etc. are all use NSURLSession.

1. NSURLSession Overview.

The NSURLSession class is used as a session layer that manages the creation, maintenance and release of network communication. NSURLSession will process all underlying work for us, we just need to care about the business logic based on the NSURLSession layer.

NSURLSession and NSURLSessionConfiguration are used to replace NSURLConnection. It also provide NSURLSessionDataTask, NSURLSessionUploadTask and NSURLSessionDownloadTask which are subclass of NSURLSessionTask, different task class is used for different purpose.

Below is a picture to show the relationship of all those classes.

ios nsurlsession and sub classes

Below picture is the NSURLSessionTask and the three subclass inheritance relationships.

ios nsurlsessiontask and subclass relationship

  1. NSURLSessionDataTask : It is mainly used to read simple data on the server side, such as JSON data.
  2. NSURLSessionDownloadTask: The main purpose of this task is to download files. It does more processing for large file network requests, such as download progress, break point continuation, and so on.
  3. NSURLSessionUploadTask: Opposite to the download task, this task is mainly used for sending files to the server.

2. How To Use NSURLSession To Implement Network Task.

NSURLSession use tasks to implement network request, file download or file upload. One NSURLSession can have multiple task object to do different tasks. But all the same session task can share cache and cookie data.

If you want to start one task, you must first create a NSURLSession object, then create tasks based on the NSURLSession object and then start to run the task.

2.1 Create NSURLSession Object.

There are three methods you can choose to create NSURLSession object.

  1. Create NSURLSession object directly by constructor.
    NSURLSession *session = [NSURLSession sharedSession];
  2. Create by configuration.
    [NSURLSession sessionWithConfiguration:defaultSessionConfiguration]

    There are three types of configuration for NSURLSession.

    //The default configuration stores the cache on disk
    + (NSURLSessionConfiguration *)defaultSessionConfiguration;
    //Transient session mode does not create a cache for persistent storage
    + (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
    //Background session mode allows applications to upload and download in the background
    + (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier
  3. Create by configuration and delegate.
    // Using the proxy method requires setting the proxy, but the delegate attribute of the session is read-only, and you can only create the session this way if you want to set the proxy
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
    delegateQueue:[[NSOperationQueue alloc] init]];

2.2 Create Tasks Using The NSURLSession Object.

2.2.1 Create NSURLSessionDataTask.

Create by request object or url :

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;

Create by request object or url, also specify the callback method through the completionHandler after task complete.

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
2.2.2 Create NSURLSessionUploadTask.

Create through request object, specify the file source or data source at upload time.

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL; 

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData; 

- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;

Specify callback code when the task complete through completionHandler.

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
2.2.3 Create NSURLSessionDownloadTask.

This task can be created by request, url or previous download data object, and the download task supports break point continuation.

// Create NSURLSessionDownloadTask by request. 
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request; 

// Create NSURLSessionDownloadTask by request. 
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url; 

// Create NSURLSessionDownloadTask by previous download data. 
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;

You can also specify the callback code after task completion through the completionHandler.

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;

We can specify the appropriate agent when using either of the three tasks. The proxy object structure of NSURLSession is as follows.

ios nsurlsession proxy object structure

NSURLSessionDelegate : As the base class for all proxy agent, it defines the most basic proxy method for network requests.

NSURLSessionTaskDelegate : Defines all network request task related proxy methods.

NSURLSessionDownloadDelegate : Defines proxy methods for downloading tasks, such as download progress, etc.

NSURLSessionDataDelegate : Defines normal data tasks and upload tasks proxy methods.

2.3 Start Task.

[task resume];