How to trigger a delegate method after a certain period of time?
I'm using a class which downloads a file asynchronously .. works a bit like this
// in AViewController.m
DataGetter *blueFile = [[DataGetter alloc] init];
blueFile.delegate = self;
[blueFile getData:@"http://example.com/blue-file"];
It has a delegate method which does stuff to the file once downloaded
- (void) dataGetterFinished:(DataGetter *)dataGetter
{
// code
}
This works OK in ideal conditions, but as we're dealing with a mobile device, connections are not always reliable. The connection might break off half way thru, or it might be unusably slow.
So I'm wondering how I would set up a delegate method which triggers after, say, 10 seconds, which then displays an error and stops the operation. Would I 开发者_StackOverflow中文版have to use NSTimer, or NSNotification , or some combination?
Quinn "The Eskimo!" from Apple did a two talks on network programming for iPhone at WWDC 2010. It's session 207 and 208, you can download them here: http://developer.apple.com/videos/wwdc/2010/
The simple recepie for network success is:
- Use
NSURLConnection
asynchronously. - Do not set a manual time-out using timers or any other means, the defaults are sane.
- Instead be prepared to handle for a
connection:didFailWithError:
, that will be sent for time-outs. - If needed you can manually cancel a connection using
-[NSURLConnection cancel]
, in response to user action for example.
精彩评论