在应用程序关闭的情况下在后台运行任务

时间:2011-05-25 04:14:54

标签: iphone

我正在创建一个应用程序,我使用drop box sdk从dropbox下载一个大文件。下载功能的工作方式是调用downloadFile方法并向其传递一个委托,它将在文件开始下载时以及文件完全下载后回调。

但是,现在如果正在下载文件并关闭应用程序,则文件下载会暂停,直到用户返回应用程序。

我尝试使用以下代码但是当我关闭应用程序时,在您返回应用程序之前,下载仍然无法完成。

UIApplication* app = [UIApplication sharedApplication];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{


     //This call calls the sdk to start downloading the file. That method will then
     // call this classes delegate methods with the progress of the download as well
     // as when the file is totally finished downloading
     [DBUtils downloadFile:fileVO.filename withHash:fileVO.filehash withRestClient:self.restClient];


    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
});

我知道如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我猜DBUtils downloadFile:...是一种异步方法。如果是这种情况,您正在做的是开始下载,然后立即结束后台任务。

你应该做的是在DBUtils上设置一个委托方法,让你的类知道下载完成后,然后从那里调用endBackgroundTask。