Yesterday translated an article on the use of nsurlsession, address: http://www.cnblogs.com/JackieHoo/p/4995733.html, The original article is from Apple's official introduction of Nsurlsession technology to achieve network request principle, the article mentions that nsurlsession network request technology is nsurlsession this new class and its related classes of suite collection. In this article today, I will focus on several important classes of the next Nsurlsession suite.
First, let's take a look at the following picture:
It can be seen that nsurlsession is mainly composed of nsurlsessionconfiguration and an optional agent. In order to complete the network request we need to create the Nsurlsessiontask object.
Nsurlsessionconfiguration
There are three ways to create nsurlsessionconfiguration:
1.defaultSessionConfiguration
2.ephemeralSessionConfiguration
3.backgroundSessionConfiguration
These three ways we have already introduced in the previous article, when we created the nsurlsessionconfiguration, we can also set some of its other properties, such as the following code of several common properties:
nsurlsessionconfiguration*sessionconfig =[Nsurlsessionconfiguration defaultsessionconfiguration];//do not allow mobile networks, only allow WiFi to operate network requests. sessionconfig.allowscellularaccess=NO;//allow only JSON data to be accepted[sessionconfig sethttpadditionalheaders: @{@"Accept":@"Application/json"}]; //set the request time-out to 30 secondssessionconfig.timeoutintervalforrequest=30.0;//set the maximum time for resource processingSessionconfig.timeoutintervalforresource=60.0;//set the maximum number of connections the app has for a single hostSessionconfig.httpmaximumconnectionsperhost=1;
Of course there are other properties that you can view in-depth documentation.
Nsurlsession
Nsurlsession is designed to replace nsurlconnection technology. The session handles network requests through its task Nsurlsessiontask object. With Nsurlsession you can easily use the method with block, agent and so on. Let's give an example:
//image address of Baidu iconNSString*imageurl =@"Https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"; //session configuration set to default configurationnsurlsessionconfiguration*sessionconfig =[Nsurlsessionconfiguration defaultsessionconfiguration];//initializing a session with the default configurationnsurlsession*session =[Nsurlsession sessionwithconfiguration:sessionconfigDelegate: Self delegatequeue:nil]; //Create a download picture taskNsurlsessiondownloadtask*getimagetask =[Session Downloadtaskwithurl:[nsurl Urlwithstring:imageurl] Completionhandler:^ (Nsurl *Location , Nsurlresponse*response, Nserror*error) { //Picture Download complete execution of block, where we process the pictureUIImage*downloadedimage =[UIImage imagewithdata: [NSData datawithcontentsofurl:location]]; //main thread Update interfaceDispatch_async (Dispatch_get_main_queue (),^{ // _imageview.image=Downloadedimage; });}]; //Remember, the task is suspended by default, and after the task is created, the resume method needs to be called if it needs to be executed immediately[Getimagetask resume];
Implement Nsurlsessiondownloaddelegate
We can implement this proxy method to notify the download task to complete:
-(void) Urlsession: (Nsurlsession *) session **) location{ // called when the download is complete }
You can also implement this agent to track download progress:
-(void) Urlsession: (Nsurlsession *) session *) downloadtask didwritedata: (int64_t) Byteswrittentotalbyteswritten: (int64_t) Totalbyteswrittentotalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite{ NSLog (@ "%f/%f", (double) Totalbyteswritten, (double) totalbytesexpectedtowrite);}
Nsurlsessiontask
We often use Nsurlsessiondatatask, Nsurlsessiondownloadtask, nsurlsessionuploadtask tasks, in fact they have a common parent class nsurlsessiontask. Their inheritance relationship is shown in the following:
The inheritance relationship between them has been clearly stated in the diagram, so let's look at the different roles of the several tasks:
Nsurlsessiondatatask
This task class is used to send a GET request for HTTP, and then download the NSData type of data. We then convert the data to a corresponding type such as Xml,json,uiimage,plist. Here's how to use it:
Nsurlsessiondatatask *jsondata = [Session datataskwithurl:yournsurl Completionhandler:^ (NSData * Data, *response, *error) { // We handle nsdata in this case as the correct datatype }];
Nsurlsessionuploadtask
As the name implies, this task class is primarily used to upload data to the Web server via post and put. Its proxy method also allows the program to understand the status of the network transport. Here's how to use an example of uploading a picture:
0.6*uploadtask = [uploadsession uploadtaskwithrequest:request fromdata:imagedata];
Nsurlsessiondownloadtask
Nsurlsessiondownloadtask-class Wet download files are super simple and allow the program to control download pauses and launches at any time. This subclass is a little bit different from the previous Sonata task class:
1. The contents of the download are written in a temporary file
2. During the download process, the session calls the URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: method to update the status information.
3. When the task download is complete URLSession:downloadTask:didFinishDownloadingToURL: The method is called. At this point we'd better move the file from a temporary location to a permanent location, or open the process immediately.
4. When the download fails or cancels, the data that the program can obtain can then resume downloading.
These features are useful with wood, but it's important to remember that all of these tasks are suspended by default when they are created and, if they are to work, to perform the resume method, for example:
[Uploadtask resume];
Well, the Nsurlsession suite implements the technical needs of the network request to use the main classes introduced here, the next article, I will be a complete example of the use of the Nsurlsession suite, and implement network requests.
Introducing the Nsurlsession Network request Suite