IOS network development NSURLSession (I) Overview, iosnsurlsession
Original blog. For more information, see blog.csdn.net/hello_hwc.
My IOS-SDK detail column, welcome to attention
Http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html
Preface:
This series of IOS network programming articles, including NSURLSession3 (An Overview, a detailed description of the use of three tasks and delegate, and an explanation of authorization and certificates ), two basic network knowledge articles (one rest api explanation has been completed, one article I will summarize the concepts encountered during the blog writing process), and one article on the use of the AFNetWorking library. This is a preliminary plan. If the content found in the writing process is incomplete, add a few more articles as appropriate.
This article may be a bit boring, but I think it is very important to understand the subsequent content, so I wrote it first.
I. Overview
NSURLSession is a group of relatively easy-to-use network APIs provided by the ios sdk. It includes several parts: NSURLRequest, NSURLCache, NSURLSession, NSURLSessionConfiguration, and NSURLSessionTask. In addition to NSURLSession, IOS network programming can also use NSURLConnection, but the latter is easy to use. Network Development consists of five parts:
Supported protocols (such as http)
Authorization and certificate (for example, the server requires a user name and password)
Cookie storage (for example, do not store cookies)
Cache Management (for example, only in the memory cache, not in the hard disk)
Configuration Management (such as http headers and other configuration information)
Ii. Brief Introduction to several core classes of NSURLSession
You just need to know what these classes are.
1.1 NSURLSessionConfiguration
Specifies the configuration information of NSURLSession. The configuration information determines the NSURLSession type, HTTP additional headers, request timeout time, Cookie acceptance policy, and other configuration information. For more information, see the official documentation.
Here we will explain in detail the three nsurlsessionconfigurations, which determine the NSURLSession types.
+ (NSURLSessionConfiguration *)defaultSessionConfiguration
DefaultSession: uses a hard disk-based persistent session Cache to save your certificate to the key string, and uses SHARED cookie storage.
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration
The configuration information is roughly the same as that of default. Besides, the cache, certificate, or any Session-related data will not be stored on the hard disk, but stored in the memory. The lifecycle is consistent with that of the Session. For example, you can use the features such as seamless browser browsing.
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier
Create a session that can still transmit data when the background or even when the APP is disabled. Note that the background Session must be assigned a unique identifier when it is created, so that the APP can be differentiated based on identifier when it is run next time. If the APP is disabled, the IOS system will close all background sessions. In addition, the IOS system does not automatically wake up the APP after it is forcibly disabled by the user. Data Transmission will continue only when the user starts the APP next time.
1.2 NSURLSessionTask
The actual Session task is divided into three types: inheritance relationship
Where,
DataTask-is used to request resources, the server returns data, and the memory is stored in NSData format. Default, ephemeral, shared Session supports data tasks. The background session is not supported.
The Upload Task-is similar to the DataTask, but the request body is provided during the request. In addition, the background Session supports upload tasks.
Download Task-Download content to the hard disk. All types of sessions are supported.
Note that all created tasks are suspended and need to be resume for execution.
1.3 NSURLSession
Session is a core component developed based on the NSURLSession network. Configured by the Configuration above, and then created NSURLSessionTask as a factory for actual data transmission tasks.
An example of initialization,
self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
Create a task
NSURLSessionDataTask * dataTask = [self.session dataTaskWithURL:[NSURL URLWithString:imageURL] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { }];
Start a task
[dataTask resume];
1.4 NSURLRequest
Specify the request URL and cache policy.
For example, the following initialization Function
(instancetype)requestWithURL:(NSURL *)theURL
cachePolicy:(NSURLRequestCachePolicy)cachePolicy
timeoutInterval:(NSTimeInterval)timeoutInterval
The url, cachePolicy, and timeoutInterval are specified during initialization.
You can set HTTPMethod through NSURLRequest. The default value is GET.
1.5 NSURLCache
The response returned by the cache URL request.
The NSURLRequest object is mapped to the NSCachedURLResponse object. You can set the cache size in the memory and the cache size and path on the disk.
If not, use Shared Cached. If necessary, create an NSURLCache object and set it through + setSharedURLCache.
Of course, the current cache Usage can also be obtained through this class.
1.6 NSURLResponse/NSHTTPURLResponse
When you use REST APIs to perform resource operations, a request must have a response ). NSURLResponse contains metadata, such as the returned Data Length (expectedContentLength), MIME type, and text encoding method.
NSHTTPURLResponse is a subclass of NSURLResponse. Because most REST tasks are HTTP, we usually encounter NSHTTPURLResponse objects. This object can be used to obtain information such as HTTP headers and status Code.
HTTP headers contains a lot of information. If you do not know it, you can check the content of http headers on the wiki.
Status code returns the Request status, for example, 404 is not found.
WWW-Authenticate: Basic realm = "nmrs_m7VKmomQ2YM3:" indicates that the Server requires the Client to perform http ba authorization.
1.7 NSURLCredential-used to process Certificate Information
For example, username and password, for example, server authorization.
This should be handled according to different authentication methods,
For example, the following describes how to initialize a user name and password authentication.
(NSURLCredential *)credentialWithUser:(NSString *)user
password:(NSString *)password
persistence:(NSURLCredentialPersistence)persistence
Certificate-based
+credentialWithIdentity:certificates:persistence:.
Here
Typedef NS_ENUM (NSUInteger, NSURLCredentialPersistence) {NSURLCredentialPersistenceNone, // does not store secrets, // stores secrets according to the Session lifecycle, // stores them to the key string keys, other devices are allocated according to the same AppleID .};
1.8 NSURLAuthenticationChallenge
When accessing resources, the server may return the required authorization (provide an NSURLCredential object ). Then, URLSession: task: didReceiveChallenge: completionHandler: called. The required authorization information is stored in the object of this class.
Several common attributes
Error
Error message of the last Authorization failure
FailureResponse
Error message of the last Authorization failure
Previusfailurecount
Number of failed authorizations
ProposedCredential
Recommended Certificate
ProtectionSpace
The NSURLProtectionSpace object includes the address port and other information. Next, we will explain this object.
1.9 NSURLProtectionSpace
This class object represents a region on the server that requires authorization information. It is called realm in English. The information of this object is used to respond to Challenge.
For example, if the server requires a user name and password-based authentication, you should first refer to the host, port, realm, protocol, and other information of the NSURLProtectionSpace object, and then provide the certificate according to this information.
Three proxies delegate
The NSURLSession proxy usually has two levels: Session level and Task level (a Session can contain multiple tasks ).
NSURLSessionDelegate-process Session-level events
NSURLSessionTaskDelegate-process all types of Task-level common events
NSURLSessionDownloadDelegate-process the Download Task level event NSURLSessionDataDelegate-process the Download Task level event
For specific proxy events, I will explain them in future demos.
If you want to learn more about IOS network development, you can read the official documents.
Https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html