NSURLSession vs NSURLConnection by Santiapps.com Marcio Valenzuela

Fetching data from an iOS app – The new NSURLSession API

NSURLSession vs NSURLConnection by Santiapps.com Marcio Valenzuela
NSURLSession vs NSURLConnection by Santiapps.com Marcio Valenzuela

Ok, this is gonna be short, I promise! 🙂

Do you remember those apps you’ve got stored away or the ones you are working on that fetch data from the web with a NSURLConnection? Time to update them, here’s how.

Basically you have a method that calls a web fetch and is somehow signaled to use that received data to refresh a UI. If you used NSURLConnection sendAsynchronousRequest:, you have the issue that it blocks the main thread. It does carry out requests asynchronously from each other, but each request does indeed block the main thread since it is carried out in the main queue. Alternatively, you can use a long brittle bunch of API’s named NSURLConnection initWithRequest: with a set of delegate callbacks. Instead, take a look at this.

If you have:

-(void)fetchDataFromWeb{
//1. LOAD DATA FROM WEB
NSURL *stringURL = [NSURL URLWithString:@"http://www.yourserver.com/appfolder/somewebserviceURL.php"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:stringURL];
[NSURLConnection sendAsynchronousRequest:myRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

//Once data is got, load local object & fire reloadData
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

//UPDATE CURRENT VIEW FIRST
[self setData];

}];
}

Replace with:

-(void)fetchDataFromWeb{
//1. LOAD DATA FROM WEB
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://www.yourserver.com/appfolder/somewebserviceURL.php"]
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
// handle response
//Once data is got, load local object & fire reloadData
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

//UPDATE CURRENT VIEW FIRST
[self setData];

}] resume];
}

The most important thing to note here, is perhaps an little noticed piece of code in NSURLConnection, queue:[NSOperationQueue mainQueue].

You see, other than that, the both pieces of code do pretty much the same thing. They fetch data. NSURLConnection fetches data but it will block your main thread. This means that if you call the fetch, your app will stop or hand until the NSURLResponse is received.

You could go this route:

1. Adopt the delegate:
& create a data container NSMutableData *_responseData;

2. Call your web fetch:
// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.yourserver.com/appfolder/somewebserviceURL.php"]];

// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

3. Get your data from the callbacks:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}

– (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//UPDATE CURRENT VIEW FIRST
[self setData];
}

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
}

That’s a BIG block of code! And it can get tedious & brittle to maintain.

NSURLSession automatically calls the web fetch in a background thread so as to not block your main thread. How cool is that? 🙂 Enjoy!

Advertisements

One thought on “Fetching data from an iOS app – The new NSURLSession API

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s