December 2012
Intermediate to advanced
834 pages
27h
English
You want to set a wait limit—in other words, a timeout—on an asynchronous connection.
Set the timeout on the URL request that you pass to the NSURLConnection class.
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=[NSURLURLWithString:urlAsString];NSURLRequest*urlRequest=[NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheDatatimeoutInterval:30.0f];NSOperationQueue*queue=[[NSOperationQueuealloc]init];[NSURLConnectionsendAsynchronousRequest:urlRequestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*error){if([datalength]>0&&error==nil){NSString*html=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];NSLog(@"HTML = %@",html);}elseif([datalength]==0&&error==nil){NSLog(@"Nothing was downloaded.");}elseif(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 ...
Read now
Unlock full access