ios 5 NSURLConnection 和待机模式下的 block 下载

标签 ios download nsurlconnection standby dispatch-async

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

这是我的代码:

-(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了解更多信息(在左侧的“应用程序状态和多任务处理”部分下)。

以下代码示例来自应用文档,可以帮助您开始使用,以便您的连接可持续长达约 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;
    });
}

关于ios 5 NSURLConnection 和待机模式下的 block 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13305780/

相关文章:

ios - FaSTLane - 更新 5 个现有屏幕截图中的 2 个屏幕截图

objective-c - UIImageView,点击和识别

objective-c - NSURLConnection 与 NSData + GCD

iphone - 遮蔽颜色后 iOS 上图像与 alpha 的边缘混合

ios - 如何使用 NSURLCache 缓存 NSURLProtocol 提供的内容

android - Phonegap 版本 : download image in one of the folders of your app

java - 是否可以从 JSP 下载二进制文件?

url - Firebase 存储共享下载 url 存在安全风险?

ios - 为什么使用 GCD 和 block 进行 HTTP 下载?

ios - 为什么 didReceiveData 函数不起作用