iOS - 如何在应用程序进入后台之前完成任务

时间:2012-03-05 14:27:39

标签: iphone ios ipad background uiapplication

我正在开发一个应用程序,当用户退出应用程序时我遇到了问题。 假设该应用正在下载3张图片。 用户退出应用程序。 我怎样才能继续下载(因为我们说的是剩下2 mo而不是500!)? 我知道这样的事情:

if ([_downloader isDownloading]) {
    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), ^{

        NSLog(@"dispatch_async debut");

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

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;

        NSLog(@"dispatch_async fin");
    });
}

问题是我的任务已在处理。我不想再次开始下载了!

你有什么想法吗?

非常感谢您的回答。

2 个答案:

答案 0 :(得分:1)

我建议使用具有内置选项的ASIHTTPRequest来恢复活动下载。 http://allseeing-i.com/ASIHTTPRequest/

答案 1 :(得分:0)

唯一的方法是使用

以同步方式下载数据
[NSData dataWithContentsOfURL:imageURL]

这种方法不是最好的。 您应该考虑创建NSOperations队列的不同方法,并在进入后台之前,存储队列并 kill 队列,您可以在应用程序返回前台时简单地恢复该队列。< / p>