开发者

How to trigger a delegate method after a certain period of time?

开发者 https://www.devze.com 2023-01-30 13:06 出处:网络
I\'m using a class which downloads a file asynchronously .. works a bit like this // in AViewController.m

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:

  1. Use NSURLConnection asynchronously.
  2. Do not set a manual time-out using timers or any other means, the defaults are sane.
  3. Instead be prepared to handle for a connection:didFailWithError:, that will be sent for time-outs.
  4. If needed you can manually cancel a connection using -[NSURLConnection cancel], in response to user action for example.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号