8.2. Handling Timeouts in Asynchronous Connections

Problem

You want to set a wait limit—in other words, a timeout—on an asynchronous connection.

Solution

Set the timeout on the URL request that you pass to the NSURLConnection class.

Discussion

When instantiating an object of type NSURLRequest to pass to your URL connection, you can use its requestWithURL:cachePolicy:timeoutInterval: class method and pass the desired number of seconds of your timeout as the timeoutInterval parameter.

For instance, if you want to wait a maximum of 30 seconds to download the contents of Apple’s home page using a synchronous connection, create your URL request like so:

NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];

NSURLRequest *urlRequest =
[NSURLRequest
 requestWithURL:url
 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
 timeoutInterval:30.0f];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection
 sendAsynchronousRequest:urlRequest
 queue:queue
 completionHandler:^(NSURLResponse *response,
                     NSData *data,
                     NSError *error) {

   if ([data length] >0  &&
       error == nil){
     NSString *html = [[NSString alloc] initWithData:data
                                            encoding:NSUTF8StringEncoding];
     NSLog(@"HTML = %@", html);
   }
   else if ([data length] == 0 &&
            error == nil){
     NSLog(@"Nothing was downloaded.");
   }
   else if (error != nil){
     NSLog(@"Error happened = %@", error);
   }

 }];

What will happen here is that the runtime will try to retrieve the contents of the provided URL. If this can ...

Get iOS 5 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.