O'Reilly logo

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

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

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