How do you know when the NSURLSession object has been invalidated by iOS?

Spilly picture Spilly · Jan 28, 2014 · Viewed 13.1k times · Source

I am seeing an error in my tests where occasionally I get the following iOS error:

A background URLSession with identifier {GUID} already exists!

Even though I call invalidateAndCancel on the NSURLSession in the cleanup call after every test. I am looking for a way to wait until I am sure the NSURLSession object has been invalidated, before proceeding to the next test.

Answer

ABeanSits picture ABeanSits · Apr 1, 2014

When you create your NSURLSession object use the sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue; method and specify yourself as the delegate.

You will then get a callback in: - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error; when the session is invalidated.

You cannot trust that invalidateAndCancel will instantly stop all tasks since it is up to the tasks to handle the cancel-call.

From the header of NSURLSession:

/* -invalidateAndCancel acts as -finishTasksAndInvalidate, but issues
* -cancel to all outstanding tasks for this session.  Note task 
* cancellation is subject to the state of the task, and some tasks may
* have already have completed at the time they are sent -cancel. 
*/