Friday, November 18, 2016

NSURLSession Advantage

NSURLConnection is deprecated in OS X 10.11 and iOS 9.0




Advantage:

  • NSURLSession also provides support for background downloads, which make it possible to continue downloading resources while your app isn’t running (or when it is in the background on iOS).
  • NSURLSession also provides grouping of related requests, making it easy to cancel all of the requests associated with a particular work unit, such as canceling all loads associated with loading a web page when the user closes the window or tab.

Main difference between NSURLSession and NSURLConnection

  • NSURLConnection: if we have an open connection with NSURLConnection and the system interrupt our App, when our App goes to background mode, everything we have received or sent were lost.
  • NSURLSession: solve this problem and also give us out of process downloads. It manage the connection process even when we don’t have access. You will need to use application:handleEventsForBackgroundURLSession:completionHandler in your AppDelegate


Example of :

NSURL *URL = [NSURL URLWithString:@"http://example.com&"];    NSURLRequest *request = [NSURLRequest requestWithURL:URL];    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { // …      
    }];
                
                
    NSURL *URL = [NSURL URLWithString:@"http://example.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSession *session = [NSURLSession sharedSession];    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { // …      
    }];
    [task resume];
                              
                              
    NSURL *URL = [NSURL URLWithString:@"http://example.com/file.zip"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler: ^(NSURL *location, NSURLResponse *response, NSError *error) {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];        NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
        NSURL *documentURL = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:documentURL error:nil];
    }];
    [downloadTask resume];
  
                                            
    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSData *data = …; NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
        // …      
    }];
    [uploadTask resume];
                                              
    //Init the NSURLSession with a configuration
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    //Create an URLRequest
    NSURL *url = [NSURL URLWithString:@"yourURL"];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    //Create POST Params and add it to HTTPBody
    NSString *params = @"api_key=APIKEY&email=example@example.com&password=password";    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
    //Create task
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //Handle your response here
    }];
    [dataTask resume];