The class for the network request (the picture from: developer.apple.com)
One, URL request
The components of a network request are the server address, the request parameters, and the request method. In iOS, a network request is represented by Nsurlrequest (or its subclass nsurlmutablerequest).
Nsurlrequest is suitable for GET requests, nsurlmutablerequest can be a POST request.
In the Get mode, both the server address and the request parameters can be contained in the URL, which can be used to create nsurlrequest (or nsurlmutablerequest) directly using the URL.
In the post mode, the server address is represented by Nsurl, and the request parameters can be encapsulated in the NSData (or saved as a file or stream). The Nsurlmutablerequest class needs to be used because the server address and request parameters need to be separated. The Nsurlmutablerequest object is created with the URL of the server address, and the NSData object that encapsulates the request parameter is added to the Nsurlmutablerequest object. Examples are as follows:
NSURL *url=[NSURL URLWithString:@“http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];NSData *data=[@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
Then add the server address and the request parameter to the Nsurlmutablerequest object:
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:60];request.HTTPMethod[email protected]"post";//指明请求方式为post,默认为getrequest.HTTPBody=data;
This prepares a network request, and the next step is how to execute the network request.
Ii. Execution of URL requests
You can use the iOS native API to perform URL requests or use a third-party library.
Two native methods for performing URL requests:
(1) nsurlsession
(2) Nsurlconnection
IOS 7.0 is recommended for use with Nsurlsession, previously using Nsurlconnection.
Nsurlsession, Nsurlconnection can send and receive data stored in NSData or file format.
Third-party libraries that implement URL requests are afnetworking, Sdwebimage, and so on.
1. Basic use of two native methods
(1) Each project has a Nsurlsession object that can be obtained by means of the [Nsurlsession Sharedsession] method, which can then be used to create a new request task. The task starts execution after calling the Resume method. There are three requests for tasks, such as uploading, downloading, and data. It is asynchronous to execute a URL request through nsurlsession.
(2) Nsurlconnection directly executes the Send method (class method) request, you can choose to synchronize or choose asynchronous. You can use block to receive data if you send the request asynchronously, or you can use a proxy. Note If you use a proxy to receive data, the data is intermittently received. It is usually convenient to use block.
The difference between synchronous and asynchronous is that synchronization is done after the network request method is executed, wait until the network request responds and complete the data transfer before returning, asynchronous is to send out the request immediately after the return.
2. Nsurlsession detailed
The get session can be obtained by initializing the method, or by using the default session object of the project, through the Sharedsession method. Initializing the Session object requires the proxy to be specified, and if it is specified as nil, the system default proxy is used.
(1) Classification of Session
The session is divided into 3 types:
- Default session: Saves the stored data to the hard disk.
- Short (ephemeral session): will not store any data to the hard disk, will only occupy memory, when the session is released, all the data will be gone.
- Backstage (background session): The difference between the default session is that it uses a separate process to process the data transfer.
You need to specify a Nsurlsessionconfiguration object when initializing the session, and the type of the session is determined by the type of the object.
(2) Classification of task tasks
The task is divided into 3 kinds, data, download, upload:
- Data Task Data task: Sending and receiving NSData form
- Download Task Download tasks: Parse data in the form of a file, enabling the app to execute in the background when it is not running.
- Upload Task upload tasks: Send data in the form of files and also support background execution.
(3) The relationship between task and session
-
The initialization of tasks and the management of tasks are done by the session.
-
Each Session object manages the tasks it creates itself.
-
The Resume method is required after the task is created and is processed by the session.
-
Task processing is done by the agent of the session, which means that the specific processing will be written in the proxy method.
(4) Use the session to complete the background transfer
Issues to be aware of:
- Only a background-type session can create a new task that supports background transfers (download task or upload task). And the background upload only supports file upload, if the upload is NSData object or data stream, after the app exits will be broken off.
- Background tasks only support HTTP and HTTPS protocols and do not support custom protocols.
- If the background transfer task is initialized after the app has entered the background, then the discretionary property value of the session's Nsurlsessionconfiguration object is true.
- Because a network error caused a background upload or background download task to fail, the system automatically re-attempts to perform these tasks, so you do not have to write your own code to re-execute the failed background task.
Background tasks interact with the app:
Background tasks are characterized by running in the background, while the background task can still run when the app is not running.
As mentioned above, the task is handled by the session of the proxy method to complete, but when the app is not running, the session has been released, this time the background task and create this task of the session back together?
This problem the iOS system has a complete set of mechanisms to deal with it. This is true: when the background task is complete or requires authentication, if the app is not running, the system will wake the app and invoke the app delegate (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler method. This method is specifically written to handle background tasks, the following describes the contents of this method to expand.
Need to rewrite in this method, in this method let the background task and the session re-associate together. Since the session that created it has been released, it is not possible to retrieve it, the actual practice is to create a session like it and then associate the task with the session. The specific is to use this method parameter identifier to create a new Nsurlsessionconfiguration object, and use this Nsurlsessionconfiguration object to create a new session, This session can be considered as the original session. The magic is that as long as the session is created, the task that is running will automatically be associated with it, as to how it is done, no need to worry about, the system has been solved.
Note that this method has a block type of parameter completionhandler, meaning that once it is executed it indicates that the background task processing is complete, so the system will wait for Completionhandler execution since the app wakes up. To stop the app from running again. Therefore, remember to pass Completionhandler to the session agent, and in the session proxy method Urlsessiondidfinisheventsforbackgroundurlsession: Call it, This allows the app to go back into the background once the last task has been processed.
When the running task has already contacted the session again, the associated method of its agent is called, and if the background task completes, the URLSession:downloadTask:didFinishDownloadingToURL: method is called. If authentication is required, the URLSession:task:didReceiveChallenge:completionHandler: method or Urlsession:didreceivechallenge is called: Completionhandler: Method.
Official Website Example: https://developer.apple.com/library/ios/samplecode/SimpleBackgroundTransfer/Introduction/Intro.html#// apple_ref/doc/uid/dts40013416
(4) Download file
Protocol methods related to file download:
URLSession:downloadTask:didFinishDownloadingToURL:
After the file download is complete, you can get the URL of the downloaded file.
URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
Called during the download process
URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:
This method is called after the start of resuming a failed download task
URLSession:task:didCompleteWithError:
The download task is called after completion or termination, and if the task is faulted, you can get to the Nserror object
- Terminate Download task
Methods that can invoke NSURLSessionDownloadTask an object:cancelByProducingResumeData:
- Resume Download Task
That can be called session downloadTaskWithResumeData: or downloadTaskWithResumeData:completionHandler:
Here the Resumedata from the Nserror object in the protocol method URLSession:task:didCompleteWithError: UserInfo dictionary will have, corresponding to the key NSURLSessionDownloadTaskResumeData .
(5) redirect
Related protocol methods:
- (void)URLSession:(NSURLSession *)session? task:(NSURLSessionTask *)task?willPerformHTTPRedirection:(NSHTTPURLResponse *)response? newRequest:(NSURLRequest *)request? completionHandler:(void (^)(NSURLRequest *))completionHandler
This method is called when the URL request task for the default session and the temporary session management is redirected, and the redirect to the subsequent task is directly subject to redirection.
In this method, a new URL request can be obtained, and the call completionHandler(request); will allow redirection. If the call completionHandler(nil); is equivalent to rejecting the redirect. Of course, you can also call completionHandler(otherRequest); implement custom redirection.
IOS Network Request note