简体   繁体   中英

iOS - How to finish a task before the App enter background

I'm developing an App and I'm facing a problem when users quit the app. Let's say the app is downloading 3 images. The user quits the app. How can I continue the download (because we're talking about 2 mo left and not 500 !)? I know something like this :

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");
    });
}

The problem is that my task is already processing. I don't want to start again the download !

Do you have any ideas ?

Thanks a lot for your answers.

I would advise using ASIHTTPRequest that has a built in option for resuming active downloads. http://allseeing-i.com/ASIHTTPRequest/

The only way is to download the data in a synchronous way with

[NSData dataWithContentsOfURL:imageURL]

This approach is not the best. You should consider a differente approach that is to create a queue of NSOperations and, before go in background, store the queue and kill the queue, queue that you can simply restore once the app returns in foreground.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM