0

我正在使用NSURLConnection从服务器下载内容(并且我正在开发 iOS 5.0 中的 iPad 应用程序)。我希望NSURLConnection即使 iPad 处于待机状态也能继续下载。是否可以?

这是我的代码:

-(void)startDownload {

    UIDevice* device = [UIDevice currentDevice];
    BOOL backgroundSupported = NO;
    if ([device respondsToSelector:@selector(isMultitaskingSupported)])
        backgroundSupported = device.multitaskingSupported;    

    NSLog(@"\n\nbackgroundSupported= %d\n\n",backgroundSupported);

    dispatch_async(dispatch_get_main_queue(), ^ {

        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:imageURL];
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
        [conn scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [conn start];

        if (conn) {
            NSMutableData *data = [[NSMutableData alloc] init];
            self.receivedData = data;

        }
        else {  ... }
    }) ;

}

谢谢!

4

1 回答 1

1

每个应用程序都可以在后台继续执行大约 10 分钟,然后才会终止。只有某些应用程序可以在后台继续执行,例如音频/gps/蓝牙等相关应用程序。您可以在后台执行和多任务处理(在左侧的应用程序状态和多任务处理部分下)找到更多信息。

以下代码示例来自应用程序文档,可以帮助您入门,因此您的连接最多可以持续约 10 分钟 -

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you.
        // stopped or ending the task outright.
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}
于 2012-11-09T10:08:48.777 回答