Search code examples
iosios8nsurlsessiondownload-manager

NSURLDomainErrorDomain error -999 when app terminate with NSURLSession


I have big trouble with NSURLSession when i'll terminate the App. I have downloaded the apple sample: https://developer.apple.com/library/ios/samplecode/SimpleBackgroundTransfer/Introduction/Intro.html

on Apple reference.

When i start download the file download correctly. When i enter in background the download continues to. When i terminate the application and i restart the app the application enter in:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

And i catch this error:

The operation couldn't be completed. (NSURLErrorDomain error -999.)

It seems that i cannot restore download when app has been terminated. It's correct?For proceed with download i must leave application active in background?

Thank you Andrea


Solution

  • i insert this new lines of code:

    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
        BLog();
    
        NSInteger errorReasonNum = [[error.userInfo objectForKey:@"NSURLErrorBackgroundTaskCancelledReasonKey"] integerValue];
    
        if([error.userInfo objectForKey:@"NSURLErrorBackgroundTaskCancelledReasonKey"] &&
           (errorReasonNum == NSURLErrorCancelledReasonUserForceQuitApplication ||
            errorReasonNum == NSURLErrorCancelledReasonBackgroundUpdatesDisabled))
        {
            NSData *resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
            if (resumeData) {
                // resume
                NSURL *downloadURL = [NSURL URLWithString:DownloadURLString];
                NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
                if (!self.downloadTask) {
                    self.downloadTask = [self.session downloadTaskWithRequest:request];
                             }
    
                [self.downloadTask resume];
                if (!_session){
                   [[_session downloadTaskWithResumeData:resumeData]resume];
                                             }
            }
        }
    }
    

    It catch NSURLErrorCancelledReasonUserForceQuitApplication but when the application try to [[_session downloadTaskWithResumeData:resumeData]resume]

    reenter again in:

    • (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

    and give me again -999 error.