IOS Network Request Nsurlsession

Source: Internet
Author: User

A significant change in IOS 7 and Mac OS X 10.9 Mavericks is the thorough refactoring of the Foundation URL loading system.

There are people who are doing research into Apple's network layer infrastructure, so I think it's time to share some of my thoughts and insights on these new APIs, how the new API will affect how we write programs, and how they affect API design concepts.

Nsurlconnection is an abstraction on top of the API of the Core foundation/cfnetwork Framework, which was released in 2003 as the first version of Safari was released. The name nsurlconnection, in effect, refers to a series of associated components in the URL loading system of the Foundation framework: Nsurlrequest, Nsurlresponse, Nsurlprotocol, Nsurlcache, Nshttpcookiestorage, Nsurlcredentialstorage, and class nsurlconnection of the same name.

Nsurlrequest was passed to Nsurlconnection. The entrusted object (subject to the previous informal agreement <NSURLConnectionDelegate> and <NSURLConnectionDataDelegate>) asynchronously returns a Nsurlresponse And a nsdata that contains the information returned by the server.

Before a request is sent to the server, the shared cache information is queried first, and then a response that has been cached may be returned immediately, depending on the policy and availability (availability). If no cached response is available, the request caches its response according to the policy we specify so that future requests can be used.

During the process of sending the request to the server, the server may issue a authentication query (authentication challenge), which can be automatically responded to by a shared cookie or secret store (credential storage) or by a delegated object. Requests in the send can also be intercepted by registered Nsurlprotocol objects to seamlessly change their loading behavior when necessary.

Anyway, Nsurlconnection has served thousands of IOS and Mac OS programs as a network infrastructure and has done quite well. But over the years, some use cases-especially on iphones and ipads-have challenged several of Nsurlconnection's core concepts, giving Apple reason to refactor it.

On the WWDC of 2013, Apple unveiled Nsurlconnection's successor: Nsurlsession.

Like Nsurlconnection, nsurlsession refers not only to the same name class Nsurlsession, but also to a series of interrelated classes. Nsurlsession includes the same components as before, Nsurlrequest and Nsurlcache, but replaces nsurlconnection with Nsurlsession, Nsurlsessionconfiguration, and 3 subcategories of Nsurlsessiontask: Nsurlsessiondatatask,nsurlsessionuploadtask,nsurlsessiondownloadtask.

The most straightforward improvement of nsurlsession compared to nsurlconnection is the ability to configure caching, protocols, cookies, and certificate policies (credential policy) for each session, and even share this information across programs. This allows the program and network infrastructure to be independent of each other without interference. Each Nsurlsession object is initialized by a Nsurlsessionconfiguration object that specifies the policies that you just mentioned and some new options for enhancing performance on mobile devices.

Another chunk of Nsurlsession is the session task. It handles the loading of data and the uploading and downloading of files and data between the client and the server. The biggest similarity between Nsurlsessiontask and Nsurlconnection is that it is also responsible for loading data, the biggest difference being that all tasks share their creator nsurlsession, the public delegate (common delegate).

Let's go into the task and discuss Nsurlsessionconfiguration later.

Nsurlsessiontask
Nsurlsessiontask is a abstract subclass, with three concrete subclasses the is used Directly:nsurlsessiondatatask, NSU Rlsessionuploadtask, and Nsurlsessiondownloadtask. These three classes encapsulate the three essential networking tasks of modern applications:fetching data, such as JSON O R XML, and uploading and downloading files.

Nsurlsessiontask is an abstract class under which 3 entity subclasses can be used directly: Nsurlsessiondatatask, Nsurlsessionuploadtask, Nsurlsessiondownloadtask. These 3 subclasses encapsulate the three most basic network tasks of modern programs: getting data, such as JSON or XML, uploading files and downloading files.

Nsurlsessiontask class Diagram

When a nsurlsessiondatatask completes, it carries the associated data, and at the end of a nsurlsessiondownloadtask task, it brings back a temporary file path to the downloaded file. As a general rule, the server's response to an upload task will also have related data returned, so Nsurlsessionuploadtask inherits from Nsurlsessiondatatask.

All tasks can be canceled, paused, or resumed. When a download task is canceled, the option is used to create a recovery data, which can then be passed to the next newly created download task in order to continue the previous download.

Unlike using the Alloc-init initialization method directly, a task is created by a nsurlsession. Each task's construction method has two versions of the block that should or does not completionhandler, for example: There are two construction methods –datataskwithrequest: and –datataskwithrequest: Completionhandler:. This is similar to Nsurlconnection's-sendasynchronousrequest:queue:completionhandler: Method, by specifying Completionhandler this block will create an implicit Delegate to replace the original delegate--session of the task. We need to use this version without Completionhandler for the default behavior of the delegate that needs to override the original session task.

Nsurlsessiontask's factory approach
In IOS 5, Nsurlconnection added SendAsynchronousRequest:queue:completionHandler: This approach, for one-time use of request, greatly simplifies the code, and it is also SendSynchronousRequest:returningResponse:error: Asynchronous alternative to this method:

Nsurl *url = [Nsurl urlwithstring:@ "http://example.com"];
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

[Nsurlconnection Sendasynchronousrequest:request
Queue:[nsoperationqueue Mainqueue]
completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *error) {
// ...
}];
Nsurlsession continues this pattern on the method of constructing a task. The difference is that instead of running the task immediately, it returns the Task object first, allowing us to configure it further, and then using the Resume method to get it to run.

The Data task can be created by Nsurl or nsurlrequest (using the former equivalent to using a nsurlrequest for a standard GET request for that URL, which is a quick Method):

Nsurl *url = [Nsurl urlwithstring:@ "http://example.com"];
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

Nsurlsession *session = [Nsurlsession sharedsession];
Nsurlsessiondatatask *task = [Session Datataskwithrequest:request
Completionhandler:
^ (NSData *data, Nsurlresponse *response, Nserror *error) {
// ...
}];

[Task resume];
Upload task creation requires a request, plus an NSData object to upload or a nsurl for the path of a local file:

Nsurl *url = [Nsurl urlwithstring:@ "Http://example.com/upload"];
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
NSData *data = ...;

Nsurlsession *session = [Nsurlsession sharedsession];
Nsurlsessionuploadtask *uploadtask = [Session Uploadtaskwithrequest:request
Fromdata:data
Completionhandler:
^ (NSData *data, Nsurlresponse *response, Nserror *error) {
// ...
}];

[Uploadtask resume];
The Download task also requires a request, except that the block is Completionhandler. The data task and the upload task are returned one time when the task is completed, but the Download task is a little bit of writing to the local temporary file. So in this block of completionhandler, we need to move the files from a temporary address to a permanent address to save them:

Nsurl *url = [Nsurl urlwithstring:@ "Http://example.com/file.zip"];
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

Nsurlsession *session = [Nsurlsession sharedsession];
Nsurlsessiondownloadtask *downloadtask = [Session Downloadtaskwithrequest:request
Completionhandler:
^ (Nsurl *location, Nsurlresponse *response, Nserror *error) {
NSString *documentspath = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) Firstobject];
Nsurl *documentsdirectoryurl = [Nsurl Fileurlwithpath:documentspath];
Nsurl *newfilelocation = [Documentsdirectoryurl urlbyappendingpathcomponent:[[response URL] lastPathComponent]];
[[Nsfilemanager Defaultmanager] copyitematurl:location tourl:newfilelocation Error:nil];
}];

[Downloadtask resume];
This code in the original note and the above statement have some questions, see this issue, this article has been corrected, if you have different views, please give us feedback on Github.

The delegate method of Nsurlsession and Nsurlconnection
Overall, the delegate method of Nsurlsession is a significant improvement in the AD-HOC pattern during the decade of Nsurlconnection Evolution. You can view this mapping table for a complete overview.

Here are some specific observations:

Nsurlsession has both Seesion delegate methods and task delegate methods to handle authentication queries. The delegate method of the session handles issues such as server trusts, client certificate evaluation, NTLM and Kerberos protocols, while task delegate handles issues based on network requests, such as Basic,digest, as well as generation Authentication (Proxy authentication), and so on.

There are two delegate methods in nsurlconnection to indicate that a network request has ended:-connectiondidfinishloading in Nsurlconnectiondatadelegate: and -connection:didfailwitherror in Nsurlconnectiondelegate: Instead of a delegate method in Nsurlsession: Nsurlsessiontaskdelegate -urlsession:task:didcompletewitherror:

The parameter type in Nsurlsession that indicates how many bytes are transferred is now changed to int64_t, and the type of the corresponding parameter in Nsurlconnection is long long.

Because of the addition of Completionhandler: The block as a parameter, Nsurlsession actually introduces a completely new pattern to the Foundation framework. This mode allows the delegate method to run safely on the main thread without blocking the main thread; delgate simply calls Dispatch_async to switch to the background for related operations, and then calls Completionhandler when the operation is complete! Can. At the same time, it can effectively have multiple return values without requiring us to use clumsy parameter pointers. Take Nsurlsessiontaskdelegate's-urlsession:task:didreceivechallenge:completionhandler: Methods to illustrate, CompletionHandler Accepts two parameters: Nsurlsessionauthchallengedisposition and Nsurlcredential, the former is the strategy to deal with the authentication query, the latter is the certificate that needs to be used (only the current person-the policy that should be used to deal with the authentication query is the use certificate, i.e. Nsurlsessionauthchallengeusecredential is valid, otherwise the parameter is NULL)

To see more information about session task, you can view WWDC session 705: "What's New in Foundation Networking"

Nsurlsessionconfiguration
The Nsurlsessionconfiguration object is used to initialize the Nsurlsession object. Nsurlsessionconfiguration has extended the setup options for the network request layer previously provided by Nsmutableurlrequest, providing us with considerable flexibility and control. From specifying available networks, to cookies, security, caching policies, to using custom protocols, setting up event settings, and several new properties for mobile device optimization, you'll find that using nsurlsessionconfiguration you can find almost any option you want to configure.

Nsurlsession will copy the Nsurlsessionconfiguration object that configures it at initialization time and save it to its own configuration property, and this property is read-only. Therefore, modifying the configuration object that was originally configured for the session will have no effect on the session. That is, the configuration is read only once during initialization and will not change after that.

Nsurlsessionconfiguration's factory approach
Nsurlsessionconfiguration has three class factory methods, which is a good illustration of the different usage scenarios considered in nsurlsession design.

+defaultsessionconfiguration returns a standard configuration, which is actually the same as the Nsurlconnection network stack (networking stack), with the same shared Nshttpcookiestorage, shared Nsurlcache, and shared nsurlcredentialstorage.

+ephemeralsessionconfiguration returns a preset configuration in which caches, cookies, and certificates are not persisted for storage. This is ideal for implementing a feature like secret browsing.

+backgroundsessionconfiguration: (NSString *) identifier is unique in that it creates a background session. The background session is different from the regular, normal session, and it can even run upload and download tasks in the event that the application hangs, exits, or crashes. The identifier specified at initialization is used to provide context to any daemon (daemon) that may resume background transport outside the process.

To see more information about the background session, you can view WWDC session 204: "What's New with multitasking"

Configuration Properties
Nsurlsessionconfiguration has 20 configuration properties. Mastering the usefulness of these configuration attributes allows applications to take full advantage of their network environment.

Basic Configuration
HTTPADDITIONALHEADERS Specifies a default set of data headers that can be set for outbound requests (outbound request). This is useful for sharing information across sessions, such as content types, languages, user agents, and identity authentication.

NSString *userpasswordstring = [NSString stringwithformat:@ "%@:%@", user, password];
NSData * Userpassworddata = [userpasswordstring datausingencoding:nsutf8stringencoding];
NSString *base64encodedcredential = [Userpassworddata base64encodedstringwithoptions:0];
NSString *authstring = [NSString stringwithformat:@ "Basic%@", base64encodedcredential];
NSString *useragentstring = @ "Appname/com.example.app (IPhone 5s; IOS 7.0.2; scale/2.0) ";

Configuration. Httpadditionalheaders = @{@ "Accept": @ "Application/json",
@ "Accept-language": @ "en",
@ "Authorization": authstring,
@ "User-agent": useragentstring};
Networkservicetype distinguishes between standard network traffic, VoIP, voice, video, and traffic used by a background process. Most applications do not need to set this.

Allowscellularaccess and discretionary are used to conserve bandwidth over cellular connections. For background transfers, it is recommended that you use the discretionary attribute instead of allowscellularaccess, as the former takes into account the availability of WiFi and power.

Timeoutintervalforrequest and Timeoutintervalforresource Specify a time-out interval for requests and resources, respectively. Many developers try to use timeOutInterval to limit the total time it takes to send a request, but what it really means is the time between the groupings (packet). In fact, we should use Timeoutintervalforresource to specify the total time for the overall timeout, but it should be used only for background transfers, not anything the user might actually want to wait for.

Httpmaximumconnectionsperhost is a new configuration option for the URL loading system in the Foundation framework. It was once used by nsurlconnection to manage private connection pools. Now with nsurlsession, developers can limit the number of connections to specific hosts when they need to.

Httpshouldusepipelining This property is also available under Nsmutableurlrequest, which can be used to turn on HTTP pipelining (HTTP pipelining), which can significantly reduce the load time of the request. However, because it is not widely supported by the server, it is disabled by default.

Sessionsendslaunchevents is another new property that specifies whether the session should start from the background.

CONNECTIONPROXYDICTIONARY Specifies the proxy server in the session connection. Similarly, most consumer-facing applications do not require proxies, so it is not necessary to configure this property.

More information about connection agents can be found in Cfproxysupport Reference.

Cookie Policy
Httpcookiestorage stores the cookie used by the session. By default, Nshttpcookieshorage's +sharedhttpcookiestorage is used as the singleton object, which is the same as nsurlconnection.

Httpcookieacceptpolicy determines under what circumstances the session should accept cookies from the server.

HTTPSHOULDSETCOOKIES Specifies whether the request should use the cookie stored by the session, which is the value of the Httpcookiesorage property.

Security Policy
The Urlcredentialstorage stores the certificate used by the session. By default, Nsurlcredentialstorage's +sharedcredentialstorage is used as the singleton object, which is the same as nsurlconnection.

Tlsmaximumsupportedprotocol and Tlsminimumsupportedprotocol determine if the session supports the SSL protocol.

Caching policies
Urlcache is the cache used by the session. By default, Nsurlcache's +sharedurlcache is used as the singleton object, which is the same as nsurlconnection.

REQUESTCACHEPOLICY specifies when a cached response should is returned for a request. This was equivalent to Nsurlrequest-cachepolicy.

REQUESTCACHEPOLICY specifies when the cached response for a request should be returned. This is equivalent to the-cachepolicy method of Nsurlrequest.

Custom Protocols
Protocolclasses is used to configure an array of custom protocols that are used by a particular session (the Protocol is a subclass of Nsurlprotocol).

Conclusion
The change in the URL loading system in IOS 7 and Mac OS X 10.9 Mavericks is a natural evolution after a deliberate consideration of nsurlconnection. Overall, Apple's Foundation Framework team did an admirable job of researching and predicting the existing and emerging use cases of mobile developers, creating APIs that are very useful for everyday tasks.

Although some decisions are a setback for composable and extensibility in this architecture, Nsurlsession is still a powerful infrastructure for achieving higher levels of network functionality.

IOS Network Request Nsurlsession

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.