iOS Network Development nsurlsession (i) overview

Source: Internet
Author: User

Original blog, reproduced please specify the source BLOG.CSDN.NET/HELLO_HWC
My ios-sdk detailed column, please pay attention to
Http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html

Objective:

This iOS network programming series of 6 articles, NSURLSession3 (an overview, a detailed description of the use of three kinds of task and delegate, a description of the authorization, certificate, etc.), the basic knowledge of the network two (a REST API explanation has been written, I will write a blog in the process of meeting the concept of a summary of the use of Afnetworking Library to write an article. This is the initial plan, if the process of writing, found that the content covered incomplete, appropriate plus a few.

This article may be a bit dull, but I think the understanding of the subsequent content is quite important, so, first write it out.

An overview

Nsurlsession is a relatively easy-to-use network API provided by the iOS SDK. It consists of several parts of the nsurlrequest,nsurlcache,nsurlsession,nsurlsessionconfiguration,nsurlsessiontask. iOS Network programming in addition to Nsurlsession, you can also use the nsurlconnection, but the latter is less user-friendliness. The overall network development consists of five parts

Supported protocols (for example, HTTP)
Authorization and certificates (for example, the server requires a user name password)
cookie storage (e.g. cookies are not stored)
Cache management (e.g. only in memory cache, not cache to hard disk)
Configuration management (such as configuration information such as HTTP headers)


A brief introduction to several core classes of nsurlsession

Know that there are these classes, probably do what is OK.

1.1NSURLSessionConfiguration

Specifies the configuration information for the nsurlsession. These configuration information determines the type of nsurlsession, the additional headers of HTTP, the timeout time of the request, the cookie's acceptance policy, and other configuration information. See the official documentation for more information.

Here is a detailed explanation of the next three kinds of nsurlsessionconfiguration, which determines the nsurlsession species.

+ (NSURLSessionConfiguration *)defaultSessionConfiguration
Defaultsession, using persistent session cache based on hard disk, save user's certificate to keychain, use shared cookie storage

+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration
Configuration information is roughly the same as default. In addition, the cache, certificate, or any session-related data is not stored to the hard disk, but stored in memory, with the same lifecycle and session. such as browser non-trace browsing and other functions can be based on this to do.

+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier
Create a session that can still transmit data in the background or even when the app is closed. Note that the background session must be created with a unique identifier, so that the next time the app runs, it can be based on the identifier to make the relevant distinction. If the user closes the App,ios system, all background sessions will be closed. Moreover, after being forcibly closed by the user, the iOS system does not actively wake the app, and the data transfer will continue only if the user launches the app the next time.

1.2 Nsurlsessiontask

The actual session task, divided into three kinds, inheritance relations

which
Datatask-is used to request resources, and then the server returns data, which is then stored in the NSData format in memory. The default,ephemeral,shared session supports data task. Background session is not supported.
Upload task-and Datatask are similar, except that the request body is provided when requested. and the background session supports upload task.
Download task-download content to the hard drive, all types of sessions are supported.

Note that the created task is in a pending state and requires a resume to execute.

1.3 nsurlsession

A session is a core component that is based on nsurlsession network development. Configured by the configuration above, and then as a factory, create nsurlsessiontask to perform actual data transfer tasks.
An example of initialization,

self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

Create a task

NSURLSessionDataTask * dataTask = [self.session dataTaskWithURL:[NSURLURLWithString:imageURL] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {    }];

Start a task

    [dataTask resume];
1.4 Nsurlrequest

Specifies the URL of the request and the cache policy.
For example, the following initialization function

(instancetype)requestWithURL:(NSURL *)theURL?                   cachePolicy:(NSURLRequestCachePolicy)cachePolicy?               timeoutInterval:(NSTimeInterval)timeoutInterval

is to specify Url,cachepolicy and timeOutInterval at initialization time.

HttpMethod can be set by Nsurlrequest, by default, get

1.5 Nsurlcache

The cache URL request returns the response.

The way to do this is to map the Nsurlrequest object to the Nscachedurlresponse object. You can set the size of the cache in memory, and the size and path of the cache on disk.
It is not particularly necessary to use the shared cached enough, if there is a special need, create a Nsurlcache object, and then set by the + Setsharedurlcache.

Of course, the use of the current cache can also be obtained through this class.

1.6 Nsurlresponse/nshttpurlresponse

When a resource is manipulated through the rest API, there must be response (response) on request. The nsurlresponse contains metadata, such as the returned data length (expectedcontentlength), MIME type, and text encoding.

Nshttpurlresponse is a subclass of Nsurlresponse, and since most of the rest is HTTP, the Nshttpurlresponse object is usually encountered. This object can be used to obtain: HTTP Headers,status code and other information.
Where: HTTP headers contains more information, do not understand the wiki can see the content of the HTTP headers.
Status code returns the state of the request: for example, 404 is not found.

Www-authenticate:basic realm= "NMRS_M7VKMOMQ2YM3:" is the server requires the client to make HTTP BA authorization.

1.7 nsurlcredential-Used to process certificate information
such as user name password, such as server authorization and so on.
This is to be handled according to different authentication methods,
For example, the following is the initialization of a user name password authentication.

(NSURLCredential *)credentialWithUser:(NSString *)user?                               password:(NSString *)password?                            persistence:(NSURLCredentialPersistence)persistence

Certificate-based

+credentialWithIdentity:certificates:persistence:.

Here's

typedef NS_ENUM(NSUInteger, NSURLCredentialPersistence) {   //不存储   NSURLCredentialPersistenceForSession,//按照Session生命周期存储   NSURLCredentialPersistencePermanent,//存储到钥匙串   NSURLCredentialPersistenceSynchronizable//存储到钥匙串,根据相同的AppleID分配到其他设备。};
1.8 Nsurlauthenticationchallenge

When accessing resources, it is possible that the server will return the need for authorization (providing a Nsurlcredential object). So, URLSession:task:didReceiveChallenge:completionHandler: is called. The required authorization information is stored in the object of this class.
A few common properties
Error
Error message for last authorization failure
Failureresponse
Error message for last authorization failure
Previousfailurecount
Number of authorization failures
Proposedcredential
Recommended certificates for use
Protectionspace
The Nsurlprotectionspace object, which includes information such as the address port, is then explained in this object.

1.9 Nsurlprotectionspace

The object of this class represents an area on the server that requires authorization information, called Realm. Respond to challenge with information from this object.
For example, if the server needs a password based on the user name authentication, then should refer to the next Nsurlprotectionspace object Host,port,realm,protocol and other information, and then follow this information to provide a certificate.

Three agent Delegate

Nsurlsession agents are usually two levels, session level and task level (a session can include multiple tasks).
nsurlsessiondelegate-Handling Session level events
nsurlsessiontaskdelegate-handling all types of task-level commonality events
nsurlsessiondownloaddelegate-handling task-level events of type Download nsurlsessiondatadelegate-handling task-level events of type download

Specific agent events, I will be in the future demo to explain.

To learn more about iOS Web development, you can read the official documentation.
Https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html

iOS Network Development nsurlsession (i) overview

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.