October 2013
Intermediate to advanced
1053 pages
28h 7m
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:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{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); ...
Read now
Unlock full access