[英]What is the best way to poll data periodically from server when app is active in iOS in a separate thread?
我需要在iOS应用程序中定期轮询来自服务器的数据。 我需要在一个线程中每隔10秒执行一次,以保持UI可用。 当用户登录时,将触发此函数。我正在考虑使用NSRunLoop
和NSTimer
来实现此功能,并且可能使用AFNetworking
来获取JSON数据。
这是正确的方法吗? 应该使用GCD吗?
可能必须在主线程上完成的唯一部分是请求本身。 确定您需要请求并形成该请求可以在没有任何花哨的东西的情况下完成......
同意H2CO3,对于你的服务器来说,轮询可能会成为一个问题,而且客户端过多,但同时也同意你在任何情况下都不一定是错误的。
设置计时器......
[NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(timerFired:)
userInfo:nil
repeats:YES];
运行请求......
- (void)timerFired:(NSTimer *)timer {
NSURLRequest *request = // setup your request
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
// change my model in an observable way, or
// if we're in a vc, change my model and update the UI
// if we want to stop polling, [timer invalidate];
}
}];
NSTimer定期开火。 一旦发生火灾,一个方法(在主线程上)决定是否需要轮询(在你描述的情况下,如果在10秒的时间段内被调用,则总是'是')。 形成请求,NSURLConnection sendAsynchronousRequest:将请求的缓慢部分移出main。 当请求完成时,sendAsynch上的块会在main上运行。
诀窍是需要设置应用程序的其他部分以观察模型中的更改并更新视图。 这可能与在sendAsynch块中执行表重新加载一样简单,或者更复杂,例如设置将在模型更改时触发的KVO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.