NSURLSession
After iOS7, NSURLSession is the recommended HTTP request framework for the system. When making foreground requests, NSURLSession and NSURLConnection are not much different. For background requests, NSURLSession's more flexible advantages will be fully demonstrated.
Types of collections
The NSURLSession class provides 3 Session types:
(1) Default type: provides foreground request-related methods, supports configuration cache, identity credentials, etc.
(2) Ephemeral type: instant request type, no cache, identity credentials, etc.
(3) Background: background type, supports completing request tasks in the background.
Type of task
Request Tasks added in NSURLSession support 3 types:
(1) Data task: Use NSData objects to send and obtain data, which is generally used for short data tasks.
(2) Download task: Download data from the file and support background download.
(3) Upload task: upload data in the form of a file, and support background upload.
3. Create and configure NSURLSession:
The example code for configuring and creating NSURLSession through the NSURLSessionConfiguration class object is as follows:
//Default type
NSURLSessionConfiguration can also be configured such as cache, network mode and other parameters.
NSURLSessionConfiguration * defaultConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
//Instant type
NSURLSessionConfiguration * ephemeralConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
//Background type
NSURLSessionConfiguration * backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"SessionId"];
//Create and set session
NSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfiguration];
NSURLSession * ephemeralSession = [NSURLSession sessionWithConfiguration:ephemeralConfiguration];
NSURLSession * backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration];
4. Two ways to use NSURLSession to make network requests
NSURLSession has two ways to request network data. One is to obtain network data through block, and the other is to obtain network data through proxy callbacks. The request code through block method is as follows:
//Create session configuration object
Using proxy callbacks to requests requires compliance with the following protocol:
NSURLSessionConfiguration * defaultConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
//Create a request object
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
//Create session object
NSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfiguration];
//Add a task
NSURLSessionTask * task= [defaultSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",data);
}];
//Start the task
[task resume];
@interface ViewController ()<NSURLSessionDataDelegate>
Modify the request code as follows:
@end
NSURLSessionConfiguration * defaultConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
NSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionTask * task= [defaultSession dataTaskWithRequest:request];
The method of implementing the proxy is as follows:
[task resume];
//Start to accept data
5. Perform background download tasks
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
NSLog(@"=======%@",data);
}
//End of data acceptance
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
NSLog(@"complete: error%@",error);
}
The biggest advantage of NSURLSession is its flexibility in background downloading, using the following code for background data download:
NSURLSessionConfiguration * backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@""];
In the following callback method, you can listen for download progress:
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
NSURLSession * backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:nil];
[[backgroundSession downloadTaskWithRequest:request]resume];
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
If you click the Home button during the download process to make the application enter the background, the relevant proxy methods of NSURLSession will no longer be called back, but the download task is still in progress. When the background download is completed, it will interact with AppDelegate, and the following methods in AppDelegate will be called:
{
NSLog(@"######");
}
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
After that, the application will call the following method of the NSURLSesstion proxy in the background to notify the download result:
NSLog(@"1111");
}
//This method will be called regardless of success or failure
Finally, the following method of NSURLSesstion will be called:
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
NSLog(@"complete: error%@",error);
}
//This method will be called only if it is successfully downloaded. The file will be placed in the location location.
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
}
-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{
NSLog(@"All tasks are finished");
}
Cookie
Cookies are user credential information stored locally on the terminal in order to be the terminal identity. The fields and meanings in a cookie are defined by the server. For example, when a user logs in on a certain website, the server will return the cookie information to the terminal, and the terminal will save this information. The next time you visit this website again, the terminal will send the saved cookie information to the server, and the server will determine whether the user can log in automatically based on whether the cookie information is valid.
Two categories for cookie management in iOS:
Two classes are mainly responsible for HTTP network request cookies management in iOS, one is the NSHTTPCookieStorage class and the other is the NSHTTPCookie class.
The NSHTTPCookieStorage class adopts a singleton design pattern, which manages cookie information for all HTTP requests. The common methods are as follows:
//Get singleton object
+ (NSHTTPCookieStorage *)sharedHTTPCookieStorage;
//All Cookie Data Arrays are stored in NSHTTPCookie objects
@property (nullable , readonly, copy) NSArray<NSHTTPCookie *> *cookies;
// Set a cookie data manually
- (void)setCookie:(NSHTTPCookie *)cookie;
//Delete a cookie message
- (void)deleteCookie:(NSHTTPCookie *)cookie;
//All cookie information after deletion of a certain time is available after iOS8
- (nullable NSArray<NSHTTPCookie *> *)cookiesForURL:(NSURL *)URL;
//Get all cookie data for a specific URL
- (void)removeCookiesSinceDate:(NSDate *)date NS_AVAILABLE(10_10, 8_0);
//Set cookies for a specific URL
- (void)setCookies:(NSArray<NSHTTPCookie *> *)cookies forURL:(nullable NSURL *)URL mainDocumentURL:(nullable NSURL *)mainDocumentURL;
//Cookie data reception protocol
/*
The enumeration is as follows:
typedef NS_ENUM(NSUInteger, NSHTTPCookieAcceptPolicy) {
NSHTTPCookieAcceptPolicyAlways,//Receive all cookie information
NSHTTPCookieAcceptPolicyNever,//Do not receive all cookie information
NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain//Receive only cookie information from the main document domain
};
*/
@property NSHTTPCookieAcceptPolicy cookieAcceptPolicy;
The following two notifications on the system are related to cookie management:
//Notification sent when the reception protocol of Cookie data changes
FOUNDATION_EXPORT NSString * const NSHTTPCookieManagerAcceptPolicyChangedNotification;
//Notification sent when the managed cookie data changes
FOUNDATION_EXPORT NSString * const NSHTTPCookieManagerCookiesChangedNotification;
NSHTTPCookie is a specific HTTP request cookie data object, and the attribute method is as follows:
//The following two methods are used for object creation and initialization. Both key-value settings are made through dictionaries.
- (nullable instancetype)initWithProperties:(NSDictionary<NSString *, id> *)properties;
+ (nullable NSHTTPCookie *)cookieWithProperties:(NSDictionary<NSString *, id> *)properties;
//Returns a dictionary in the cookie data that can be used to add HTTP header fields
+ (NSDictionary<NSString *, NSString *> *)requestHeaderFieldsWithCookies:(NSArray<NSHTTPCookie *> *)cookies;
//Parse cookie data from the specified response header and URL address
+ (NSArray<NSHTTPCookie *> *)cookiesWithResponseHeaderFields:(NSDictionary<NSString *, NSString *> *)headerFields forURL:(NSURL *)URL;
//Dictionary of attributes in cookie data
@property (nullable, readonly, copy) NSDictionary<NSString *, id> *properties;
//Request response version
@property (readonly) NSUInteger version;
//Request the corresponding name
@property (readonly, copy) NSString *name;
//Request the corresponding value
@property (readonly, copy) NSString *value;
//Expiration time
@property (nullable, readonly, copy) NSDate *expiresDate;
//Requested domain name
@property (readonly, copy) NSString *domain;
//Requested path
@property (readonly, copy) NSString *path;
//Is it a safe transmission?
@property (readonly, getter=isSecure) BOOL secure;
//Whether to send only HTTP services
@property (readonly, getter=isHTTPOnly) BOOL HTTPOnly;
//Responsive documentation
@property (nullable, readonly, copy) NSString *comment;
//Relevant document URL
@property (nullable, readonly, copy) NSURL *commentURL;
//Service port list
@property (nullable, readonly, copy) NSArray<NSNumber *> *portList;