Tuesday, July 21, 2015

iOS NSURLSession refreshing bit of basics

Apple introduced NSURLSession to replace the NSURLConnection as a preferred way for networking. 

Below are the main reasons behind we using the NSURLSession. 

1. Background uploads and downloads: When creating the NSURLSession object, we get the benefits of background networking. This helps with the battery life, supports UIKit multitasking and uses the same delegate model as in-process transfers. 

2. Ability to pause and resume networking operations: It looks like with NSURLCOnnection API, any networking operation can be paused, stopped and restarted. No NSOperation sub classing is required. 

3. Configurable Container. Each URLSession is a configurable container for putting request into. For e.g. if we need to set and HTTP header option, we just need to do this once and each request in the session will have the same configuration. 

4. Subclassable and Private storage. NSURLSession is subclassable and we can configure a session to use private storage on a per session basis. This allows developer to have private storage per session basis. This allows developer to have private storage objects outage of the global stage. 

5. Improved authentication handling - Authentication is done per connection basis. When using NSURLConnection if an authentication challenge was issued, the challenge would come back for an arbitrary request, the problem with this is that we won’t know for which request this was returned.  

6. Rich Delegate model: NSURLConnection had some asynchronous block based methods. However delegate cannot be used with them. When a request is made it either works or fails even if authentication was needed. With NSURLSession, we can have a hybrid approach, use the asynchronous block based methods and also setup a delegate to handle authentication. 

7. Uploads and downloads through the file system: This encourages the separation of the data (file contents) from the metadata (the URL and settings) 

Simple requests seemed very simple as this below 

NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:@"http://api.openweathermap.org/data/2.5/weather?q=London,uk"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data !=NULL)
        {
            NSString *strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"data is :%@",strData);
        }
        //
    }] resume];


References:

No comments:

Post a Comment