2
使用iOS 4.0我試圖在應用程序暫停時在後臺下載圖像。我正在做的是,當我得到applicationDidEnterBackground
委託調用時,我啓動一個異步NSURLConnection
並將應用程序委託設置爲連接的委託。但NSURLConnection
代表都沒有回覆。我使用Wireshark捕獲了網絡電話,我可以看到我的請求成功並獲得了響應。但由於沒有任何委託方法被調用,我無法對數據做任何事情。iOS 4.0任務完成背景
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"Application entered background state.");
// UIBackgroundTaskIdentifier bgTask is instance variable
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://animal.discovery.com/mammals/leopard/pictures/leopard-picture.jpg"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO] autorelease];
[self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[self.connection start];
[request release];
NSLog(@"Sent download request....");
dispatch_async(dispatch_get_main_queue(), ^{
while([application backgroundTimeRemaining] > 1.0) {
//Do something..
}
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
NSLog(@"Ending background task....");
});
}
當應用程序轉到後臺時,我應該如何在後臺異步完成下載?
我有同樣的問題...我嘗試終止異步連接並使用同步一個代替..不知道它是否工作;) – 2010-08-14 10:09:47