我很新的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