Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 891
Andrea Bozza Avatar asked Dec 08 '22 06:12

Andrea Bozza


1 Answers

A couple of observations:

  1. Error -999 is kCFURLErrorCancelled.

  2. If you are using NSURLSessionDownloadTask, you can download those in the background using background session configuration, e.g.

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:kBackgroundIdentifier];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    

    If not using background session (e.g. you have to use data task, for example), you can use beginBackgroundTaskWithExpirationHandler to request a little time for the app the finish requests in the background before the app terminates.

  3. Note, when using background sessions, your app delegate must respond to handleEventsForBackgroundURLSession, capturing the completion handler that it will call when appropriate (e.g., generally in URLSessionDidFinishEventsForBackgroundURLSession).

  4. How did you "terminate the app"? If you manually kill it (by double tapping on home button, holding down on icon for running app, and then hitting the little red "x"), that will not only terminate the app, but it will stop background sessions, too. Alternatively, if the app crashes or if it is simply jettisoned because foreground apps needed more memory, the background session will continue.

    Personally, whenever I want to test background operation after app terminates, I have code in my app to crash (deference nil pointer, like Apple did in their WWDC video introduction to NSURLSession). Clearly you'd never do that in a production app, but it's hard to simulate the app being jettisoned due to memory constraints, so deliberately crashing is a fine proxy for that scenario.

like image 66
Rob Avatar answered Jan 21 '23 01:01

Rob