O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required