我正在使用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 { ... }
}) ;
}
谢谢!
在终止之前,每个应用程序都可以在后台继续执行大约10分钟。只有某些应用可以继续在后台执行,例如音频/ gps /蓝牙等相关应用。您可以在Background Execution and Multitasking(左下方的App States和Multitasking部分)中找到更多信息。
以下代码示例来自app doc,可以帮助您开始使用,因此您的连接可以持续大约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;
});
}