NSURLSession Past and Present

Systems Network Architecture Framework FIG.

Past -NSURLConnection

  NSURLConnection native class network access provided by Apple, has 10 years of history, from its iOS 2.0, has been to iOS9 abandoned. Asynchronous method after iOS 5.0 only, after iOS 5.0, is through a proxy way to achieve network development.

NSURLConnection commonly used class

  • NSURL: Request address
  • NSURLRequest: encapsulating a request, sent to all the data stored in the server, including a NSURL object request method, request header, the request body ....
  • NSMutableURLRequest: NSURLRequest subclass
  • NSURLConnection: responsible for sending a request to establish a connection the client and the server. NSURLRequest response data to the data server, from the server and collect

NSURLConnection use steps

  • 1. Create a NSURL object path setting request
  • 2. Create a further object via NSURLRequest NSURL, setting request header and request body
  • 3. NSURLConnection transmission NSURLRequest

The method of sending a request NSURLConnection

  • Synchronize
+ (nullable NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse * _Nullable * _Nullable)response error:(NSError **)error;
  • asynchronous
+ (void)sendAsynchronousRequest:(NSURLRequest*) request
                          queue:(NSOperationQueue*) queue
              completionHandler:(void (^)(NSURLResponse* _Nullable response, NSData* _Nullable data, NSError* _Nullable connectionError)) handler
  • proxy
- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate startImmediately:(BOOL)startImmediatel;
- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate;
+ (nullable NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate;

 

Life -NSURLSession

  In the WWDC 2013, Apple's team NSURLConnection been restructured and launched NSURLSession instead. The NSURLSession NSURLConnection replaced NSURLSession and NSURLSessionConfiguration , and three subclasses of NSURLSessionTask: NSURLSessionDataTaskNSURLSessionUploadTask , and NSURLSessionDownloadTask .

NSURLSession commonly used class

  • NSURL: Request address
  • NSURLRequest: encapsulating a request, sent to all the data stored in the server, including a NSURL object request method, request header, the request body ....
  • NSURLSessionConfiguration: mode of operation and for configuring network settings NSURLSession

  • NSURLSessionTask: Session task, created by NSURLSession
  • NSURLSessionDataTask, NSURLSessionUploadTask, NSURLSessionDownloadTask: subclasses are NSURLSessionTask
  • NSURLSession: All Task Management

NSURLSession use the steps

  • Creating a NSURL object path setting request
  • Then create a NSURLRequest objects by NSURL (can be saved)
  • Get the session object
  • According to the session object created Task
  • Start Task
    // 1. Create the URL of 
    NSURL * url = [NSURL URLWithString: @ " HTTP: // xxxx " ]; 
    
    // 2. Create a request Request 
    NSURLRequest * Request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 30 ]; 
    
    // 3. Add configuration 
    NSURLSessionConfiguration configuration * = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    
    // 5. The Create the session 
    NSURLSession the session * = [NSURLSession sessionWithConfiguration: configuration]; 
    
    // 6. The request to create a task
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSLog(@"data=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        } else {
            NSLog(@"error=%@",error);
        }
    }];
    
    //7.启动任务
    [dataTask resume];

 

The method of sending a request NSURLSession

  • General request
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
  • Upload task
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(nullable NSData *)bodyData completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
  • Download task
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;

NSURLSession NSURLConnection advantage compared to what?

  1. NSURLConnection instantiating the object is instantiated, the default request is transmitted (synchronous transmission), no need to call start method. And cancel can stop sending requests can not continue to access after stop, you need to create a new request. NSURLSession There are three control methods, cancellation (cancel), pause (suspend), continue (resume), you can continue to restore the current task request after a pause.
  2. NSURLSession configuration class NSURLSessionConfiguration, provide cookie, security and caching strategies, hosts the largest number of connections, resource management, network timeouts and other configurations. NSURLConnection this configuration can not be compared to NSURLConnection relies on a global configuration object, in terms of lack of flexibility.

  3. NSURLConnection resource data is downloaded into memory at first, and then write sandbox, download NSURLSession resource data to the sandbox, apparently NSURLConnection more memory consumption.
  4. NSURLConnection download breakpoints, set the access request by the HTTPHeaderField Range property, open cycle operation, the proxy method NSURLConnection event source as the operating cycle, when receiving the proxy method calls will continue to download data, and data streams using the pipe NSOutputStream save. NSURLSession breakpoint download, download task when paused, if downloadTask (download task) is non-empty, call cancelByProducingResumeData: completionHandler this method (void (^) (NSData * resumeData)), this method takes one parameter, the processing block is completed this block has a NSData resumeData parameter, if non-empty resumeData, we save the objects to the view controller resumeData properties. Continue to perform download operation: [self.resumeData] resume [self.session downloadTaskWithResumeData] method when you click on download again, by calling. After the above comparison can be found using NSURLSession download breakpoint more convenient. 

Guess you like

Origin www.cnblogs.com/Lanht/p/11095221.html