我很新的iOS开发和objC所以请与我裸...任务在后台运行,不会触发代表
我的应用程序必须查询服务器最多为10分钟(使用RestKit)即使应用程序发送到后台也是如此。 (轮询总是开始,而应用程序在前台)
我有一个视图控制器(不是RootViewController),它监听applicationDidEnterBackground。
此外,还有一个“Order”类,它有一个用于向服务器发送请求的“poll”方法,还有一些其他的用于“timeout”,“request cancel”,“handle response”的回调方法,等等
- (void)poll
{
RKRequest* request = [[RKClient sharedClient] requestWithResourcePath:@"/foo.php" delegate:self];
request.backgroundPolicy = RKRequestBackgroundPolicyContinue;
[request send];
NSLog(@"I am your RKClient singleton : %@", [RKClient sharedClient]);
}
- (void)requestDidStartLoad:(RKRequest *)request {
NSLog(@"requestDidStartLoad");
}
- (void)requestDidTimeout:(RKRequest *)request {
NSLog(@"requestDidTimeout");
}
- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error {
NSLog(@"didFailLoadWithError");
}
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response
{
}
虽然应用程序在前台,一切正常,回调被触发。
当我的应用程序进入后台我想继续轮询服务器。我使用这种方法,“调查”被称为,但没有回调被触发..
- (void)applicationDidEnterBackground:(NSNotification *) notification
{
Order *order = [[Order alloc] init];
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier taskId;
taskId = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:taskId];
}];
if (taskId == UIBackgroundTaskInvalid) {
return;
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
while(YES)
{
sleep(1);
[order poll];
}
[app endBackgroundTask:taskId];
});
[order release];
}
我做错了什么?
谢谢!
RKClient是RestKit的一个类。显然,问题是,当应用程序在后台没有新的异步请求可以从请求队列中派发..至少这是我的理解。将请求设置为同步后,一切正常,因为我在一个单独的线程,同步请求并没有打扰我。 :) 谢谢! – 2012-01-25 18:15:47
感谢您的澄清。绝对是的,单独线程上的同步请求运行良好,特别是如果您不需要跟踪进度,但您只对最终状态感兴趣。 – viggio24 2012-01-26 20:10:31
“将请求设置为同步后”是否仍然可以使用RKClient执行此操作? – Luka 2012-03-06 12:24:33