Introducing NSURLSESSION web request suite

Introducing NSURLSESSION web request suite

  Yesterday, I translated an article "Using NSURLSession", address: http://www.cnblogs.com/JackieHoo/p/4995733.html, the original text is from Apple’s official introduction to the principle of NSURLSession technology to achieve network requests, in the article It is mentioned that the NSURLSession network request technology is a suite of NSURLSession this new class and its related classes. Today's article, I will focus on several important classes of the NSURLSession suite.

  First we look at the following picture:

 

 

 

  It can be seen from the figure that NSURLSession is mainly composed of NSURLSessionConfiguration and an optional proxy. In order to complete the network request we need to create an NSURLSessionTask object.

 

NSURLSessionConfiguration

 

  There are three ways to create NSURLSessionConfiguration:

1.defaultSessionConfiguration 

2.ephemeralSessionConfiguration

3.backgroundSessionConfiguration

  These three methods have been introduced in the previous article. After we create NSURLSessionConfiguration, we can also set some of its other properties, such as several common properties in the following code:

 

Copy code
 

NSURLSessionConfiguration *sessionConfig = 

[NSURLSessionConfiguration defaultSessionConfiguration]; 

 

// No mobile network is allowed, only WIFI operation network request is allowed. 

sessionConfig.allowsCellularAccess = NO; 

 

// Only allow to accept json data 

[sessionConfig setHTTPAdditionalHeaders: 

          @{ @" Accept " : @" application/json " }]; 

 

// Set the request timeout to 30 seconds 

sessionConfig.timeoutIntervalForRequest = 30.0 ; 

/ / Set the maximum time for resource processing 

sessionConfig.timeoutIntervalForResource = 60.0 ; 

// Set the maximum number of connections for the app to a single host

sessionConfig.HTTPMaximumConnectionsPerHost = 1;
Copy code

 

 

  Of course, there are other attributes, you can check the document to learn more.

 

NSURLSession

 

  NSURLSession is designed to replace NSURLConnection technology. The session handles network requests through its task NSURLSessionTask object. Using NSURLSession you can easily use block methods, agents, etc. Let's give an example:

Copy code
// 百度图标的图片地址

NSString *imageUrl =

@"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";

 

// 会话配置设置为默认配置

NSURLSessionConfiguration *sessionConfig =

  [NSURLSessionConfiguration defaultSessionConfiguration];

 

// 使用默认配置初始化会话

NSURLSession *session =

  [NSURLSession sessionWithConfiguration:sessionConfig

                                delegate:self

                           delegateQueue:nil];

 

 

// 创建 下载图片任务

NSURLSessionDownloadTask *getImageTask =

[session downloadTaskWithURL:[NSURL URLWithString:imageUrl]

 

    completionHandler:^(NSURL *location,

                        NSURLResponse *response,

                        NSError *error) {

        

// 图片下载完成执行的block,在这里我们处理图片

        UIImage *downloadedImage =

          [UIImage imageWithData:

              [NSData dataWithContentsOfURL:location]];

      //主线程更新界面

      dispatch_async(dispatch_get_main_queue(), ^{

        // 

        _imageView.image = downloadedImage;

      });

}];

 

// 记住,任务默认是挂起状态的,创建任务后,如果需要立即执行,需要调用resume方法

[getImageTask resume];
Copy code

 

 

 

实现NSURLSessionDownloadDelegate

 

  我们可以实现这个代理方法,通知下载任务完成:

 

Copy code
-(void)URLSession:(NSURLSession *)session

     downloadTask:(NSURLSessionDownloadTask *)downloadTask

didFinishDownloadingToURL:(NSURL *)location

{

  //下载完成时调用

}
Copy code

 

 

 

  也可以实现这个代理来跟踪下载进度:

 

Copy code
 

-(void)URLSession:(NSURLSession *)session

     downloadTask:(NSURLSessionDownloadTask *)downloadTask

     didWriteData:(int64_t)bytesWritten

totalBytesWritten:(int64_t)totalBytesWritten

totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite

{

  NSLog(@"%f / %f", (double)totalBytesWritten,

    (double)totalBytesExpectedToWrite);

}
Copy code

 

 

 

 

NSURLSessionTask

 

 

  我们常用NSURLSessionDataTask、NSURLSessionDownloadTask、NSURLSessionUploadTask任务,其实他们有一个共同的父类NSURLSessionTask。他们的继承关系入下图所示:

 

 

  图中已经明确说明了他们之间的继承关系,下面我们来介绍一下这个几个任务的不同作用:

 

 

NSURLSessionDataTask

 

 

  这个任务类是用来发器http的get请求,然后下载NSData类型的数据的。然后我们将数据转换成XML,JSON,UIImage,plist等对应的类型。使用方法如下:

 

Copy code
NSURLSessionDataTask *jsonData = [session dataTaskWithURL:yourNSURL

      completionHandler:^(NSData *data,

                          NSURLResponse *response,

                          NSError *error) {

        // 我们在这例处理NSData为正确的数据类型

}];
Copy code

 

 

NSURLSessionUploadTask

 

 

顾名思义,这个任务类主要是用来通过post和put上传数据到web服务器的。它的代理方法还可以允许程序了解网络传输状态的。下面示范一个上传图片的例子的使用方法:

 

 

Copy code
NSData *imageData = UIImageJPEGRepresentation(image, 0.6);

 

NSURLSessionUploadTask *uploadTask =

  [upLoadSession uploadTaskWithRequest:request

                              fromData:imageData];
Copy code

 

 

 

 

NSURLSessionDownloadTask

 

  NSURLSessionDownloadTask class wet downloading files becomes super simple, and allows the program to control the pause and start of the download at any time. This subcategory is slightly different from the previous Sonata task category:

1. Write the downloaded content to a temporary file

2. During the download process, the session will call URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: method to update the status information.

3. When the task download is complete, the URLSession:downloadTask:didFinishDownloadingToURL: method will be called. At this time, we'd better move the file from a temporary location to a permanent location, or open it immediately for processing.

4. When the download fails or is cancelled, the data that the program can obtain can then continue to resume the download.

 

  These features are very useful, but it is important to remember that all these tasks are suspended by default when they are created. If they are to be effective, the resume method must be executed, for example:

 

[uploadTask resume];

 

 

  Well, the main classes needed to implement the network request technology of the NSURLSession suite are introduced here. In the next article, I will use a complete example to actually use the NSURLSession suite and implement network requests.

Guess you like

Origin blog.csdn.net/qq_27740983/article/details/51348333