14.7. Handling Network Connections in the Background

Problem

You are using instances of NSURLConnection to send and receive data to and from a web server and are wondering how you can allow your application to work in the multitasking environment of iOS without connection failures.

Solution

Make sure you support connection failures in the block objects that you submit to your connection objects.

Discussion

For applications that use NSURLConnection but do not borrow extra time from iOS when they are sent to the background, connection handling is truly simple. Let’s go through an example to see how an asynchronous connection will act if the application is sent to the background and brought to the foreground again. For this, let’s send an asynchronous connection request to retrieve the contents of a URL (say, Apple’s home page):

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
  
  NSString *urlAsString = @"http://www.apple.com";
  NSURL *url = [NSURL URLWithString:urlAsString];
  NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
  NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  
  [NSURLConnection 
   sendAsynchronousRequest:urlRequest
   queue:queue
   completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
     
     if ([data length] > 0 &&
         error != nil){
       /* Date did come back */
     }
     else if ([data length] == 0 &&
              error != nil){
       /* No data came back */
     }
     else if (error != nil){
       /* Error happened. Make sure you handle ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.