NSURLSession usage (1), nsurlsession usage
1. Create a Session and initialize it.
Three creation methods are available:
1. + (NSURLSession *) sharedSession Singleton Mode 2. + (NSURLSession *) sessionWithConfiguration :( NSURLSessionConfiguration *) configuration this is a conventional method 3. + (NSURLSession *) sessionWithConfiguration :( NSURLSessionConfiguration *) configuration delegate :( nullable id <NSURLSessionDelegate>) delegate delegateQueue :( nullable NSOperationQueue *) There are also three common configuration methods: 1. + (NSURLSessionConfiguration *) defaultSessionConfiguration general Configuration 2, + (NSURLSessionConfiguration *) ephemeralSessionConfiguration temporary Configuration 3, + (NSURLSessionConfiguration *) running: Configuration running in the background note: Setting the Configuration value does not change the current Session mode, it takes effect only when you reinitialize a Session.
NSURLSessionConfiguration * myconfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @ "backgroundsession"]; // The requested Cache Policy myconfiguration. requestCachePolicy = NSURLRequestUseProtocolCachePolicy; // The data transmission times out. When the data transmission is resumed, the myconfiguration is cleared. timeoutIntervalForRequest = 5; // a single request times out and determines the maximum lifecycle of a request. timeoutIntervalForResource = 5; // the requested service type myconfiguration. networkServiceType = NSURLNetworkServiceTypeDefault; // whether to allow the use of mobile network (Telephone Network) default is YES myconfiguration. allowsCellularAccess = YES; // The background mode takes effect. YES allows adaptive system performance adjustment. discretionary = YES; self. testSession = [NSURLSession sessionWithConfiguration: myconfiguration delegate: self delegateQueue: [NSOperationQueue currentQueue];
Ii. Implement proxy (Session-Level)
Select the third initialization method to create a Session. There will be three Session-level proxies for your use.
// Session close callback-(void) URLSession :( NSURLSession *) session didBecomeInvalidWithError :( NSError *) error {NSLog (@ "% s, % @" ,__ func __, error);} // certificate security question-(void) URLSession :( NSURLSession *) session didReceiveChallenge :( success *) challenge completionHandler :( void (^) (success, NSURLCredential * _ Nullable )) completionHandler {} // The background network task is completed // callback:-application: handleEventsForBackgroundURLSession: completionHandler:-(void) URLSessionDidFinishEventsForBackgroundURLSession :( NSURLSession *) session {}