Cover by Vandad Nahavandipoor

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required