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 are all using NSURLSession.

1. NSURLSession Overview.

  1. The NSURLSession class is used as a session layer that manages the creation, maintenance, and release of network communication.
  2. NSURLSession will process all underlying work for us, we just need to care about the business logic based on the NSURLSession layer.
  3. NSURLSession and NSURLSessionConfiguration are used to replace NSURLConnection. It also provides NSURLSessionDataTask, NSURLSessionUploadTask, and NSURLSessionDownloadTask which are a subclass of NSURLSessionTask, different task class is used for different purposes.
  4. NSURLSessionDataTask: It is mainly used to read simple data on the server-side, such as JSON data.
  5. NSURLSessionDownloadTask: The main purpose of this task is to download files. It does more processing for large file network requests, such as download progress, breakpoint continuation, and so on.
  6. 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.

  1. NSURLSession use tasks to implement network request, file download or file upload.
  2. One NSURLSession can have multiple task objects to do different tasks. But all the same session tasks can share cache and cookie data.
  3. If you want to start one task, you must first create an NSURLSession object, then create tasks based on the NSURLSession object and then start to run the task.

2.1 Create NSURLSession Object.

  1. There are three methods you can choose to create an NSURLSession object.
  2. Create NSURLSession object directly by the constructor.
    NSURLSession *session = [NSURLSession sharedSession];
  3. Create by configuration.
    [NSURLSession sessionWithConfiguration:defaultSessionConfiguration]
  4. 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
  5. 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.
  1. Create by request object or URL:
    - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;
    - (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;
  2. 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.
  1. 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;
  2. 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.
  1. This task can be created by request, URL, or previous download data object, and the download task supports breakpoint 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;
  2. 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;
  3. We can specify the appropriate agent when using either of the three tasks. The proxy object structure of NSURLSession is as follows.
  4. NSURLSessionDelegate: As the base class for all proxy agents, it defines the most basic proxy method for network requests.
  5. NSURLSessionTaskDelegate: Defines all network request task-related proxy methods.
  6. NSURLSessionDownloadDelegate: Defines proxy methods for downloading tasks, such as download progress, etc.
  7. NSURLSessionDataDelegate: Defines normal data tasks and upload tasks proxy methods.

2.3 Start Task.

  1. Run the below code to resume a task.
    [task resume];

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.