iOS 4.0任务完成背景

时间:2010-08-04 09:08:36

标签: ios multitasking

使用iOS 4.0我试图在应用程序暂停时在后台下载图像。我正在做的是当我得到applicationDidEnterBackground委托调用时,我启动一个异步NSURLConnection并将app委托设置为连接的委托。但NSURLConnection代表中没有一个被召回。我使用Wireshark捕获了网络调用,我可以看到我的请求成功并得到了响应。但由于没有调用任何委托方法,我无法对数据做任何事情。

- (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....");
});
}

当应用程序进入后台时,如何在后台异步完成下载?

1 个答案:

答案 0 :(得分:0)

我认为这是因为您在下载实际完成之前结束了后台任务。下载完成后(无论是成功还是失败),您应该在NSURLConnectionDelegate方法中调用[application endBackgroundTask:self->bgTask];,而不是在调用[self.connection start]后调用