English original Address
Using Nsurlsession
Nsurlsession and its related classes provide APIs for downloading data over HTTP. The API provides a rich proxy approach to support information authentication and background download functionality when the app is not running (for example, in iOS, app hangs).
With Nsurlsession, the client creates a series of conversations, each matching a set of related data transfer tasks. For example, to encode a Web browser, the client may need to create a session for a single tag or window. For each session, the client adds a series of tasks, Each task represents a request that points to a specific URL (or URLs after HTTP redirection).
Like most network APIs, Nsurlsession is asynchronous. If you use the system's proxy by default, you must provide a block for processing results when a transfer is completed successfully or an error occurs. If you use a custom proxy object, when the data is received from the server, The Task object invokes a custom proxy method (called when the transfer is complete for a file download).
注意:回调block是自定义代理的一个主要备选方案.如果你通过回调block的方式创建了一个任务,那么代理方法将不会再被调用.
The current status and task progress values are also available through nsurlsession and can be passed to the agent. It also supports canceling, restarting (resetting), suspending tasks, and restarting tasks from Pending, canceled, and failed states.
Understanding the concept of a URL session
The behavior of a task in a session depends on 3 factors: the type of the session (determined by the type of a previously created configuration object), the type of task, and whether the app is active in front-end when the task is created.
Types of Sessions
Nsurlsession supports three session types (determined by the type of a previously created configuration object):
- Default session type: Similar to other methods of downloading URLs (nsurlconnection). Use persistent disk cache persistence policy to store authentication information in user keychain (keychain).
- Temporary session type: does not permanently store any information (cache, authentication) on disk, all information is only saved in the memory associated with the session, and all information will be emptied when the conversation fails.
- Background session type: similar to the default session type, the difference is that there is a separate thread to handle the data transfer. There are some additional limitations to background session types, see Background Data transfer considerations below
Type of Task
In one session, Nsurlsession supports three types of tasks: loading data, downloading data, and uploading data.
- The load task type uses the NSData object to send and receive data. The use scenario is a request that transmits short data and is highly interactive with the server. Data loading can periodically return the obtained data (part of the total data), Or the entire data is processed at once through a download-completed callback. Data loading does not store the acquired data in a file, so background loading is not supported.
- The download task type receives data as a file and supports downloading in the background when the app is not running.
- The upload task type usually sends data as a file, enabling the app to upload in the background when it is not running.
Background Data transfer considerations
Nsurlsession supports background data transfer while the app is pending. Background transfers are available only in sessions created using background session configuration objects.
For a background session, because the real data transfer is performed in a separate thread and the cost of restarting a thread is relatively large, some of the features will not be supported, resulting in some of the following limitations:
- A session must provide a proxy for each delegate. (Proxy methods are the same as in-process transfers for upload and download-type sessions.)
- Only HTTP and HTTPS protocols are supported (custom protocols are not supported)
- Only two session types are supported for uploading and downloading (background loading of data is not supported).
- Redirects are automatically redirected to the URL after the redirect.
- If background data transfer is created during the app's background, the discretionary property of the configuration object is treated as true (indicating that the system chooses the best network connection configuration by itself when the program is running in the background, which can save bandwidth through the cellular connection).
The app's restart performance is slightly different in iOS and OS X.
In iOS, when a background transfer is complete or information authentication is required, iOS will automatically restart the app in the background and invoke the application of the Uiapplicationdelegate object if the app is not running at this time: Handleeventsforbackgroundurlsession:completionhandler: Method. This call provides a session ID and causes the app to restart. The app should store the complete processor (completion handler, I didn't think it would be appropriate. Create a background configuration object with the same session ID and create a session from this configuration object. This session will continue to run in the background. After that, when the session completes the last download task, The proxy object that will be sent to the session a urlsessiondidfinisheventsforbackgroundurlsession: message. The session proxy object should be called and stored to complete the processor.
In iOS and OS X, when the user re-runs the app, the app should immediately create a background configuration object that uses the session ID (which may contain multiple) that was last run with an unfinished task. The sessions are then created for these configuration objects. These newly created sessions will also continue to run in the background.
注意:必须为每一个会话正确的指定标识(在创建配置对象时指定),多个会话使用同一个标识将会导致定义不明确.
If a task is completed during app suspend, the URLSession:downloadTask:didFinishDownloadingToURL of the proxy object: The method is called.
Similarly, if the task requires information authentication, the session object will be in the calling agent's URLSession:task:didReceiveChallenge:completionHandler: Method or Urlsession: Didreceivechallenge:completionhandler: Method.
See Simple Background Transfer for an example of how to use Nsurlsession.
Life cycle and Agent interaction
For better use of nsurlsession, it is best to understand in depth the life cycle of the session and how the session interacts with its proxy object. For example, when the agent is called, when the server returns a redirect URL, processing when a task download fails, and so on.
Full session lifecycle description, see life cycle of a URL session
nscopying behavior
The session object and the Task object follow the Nscopying protocol as follows:
- When the app copies a session or Task object, it returns the object itself (no new objects are created).
- When the app copies a configuration object, it returns a newly created configuration object (a new object was created).
Reprint Please specify source: http://blog.csdn.net/qq329735967
Any questions welcome email to [email protected]
Official Apple document translation: Using Nsurlsession (i)