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.
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.
*/
Apple
"IMPORTANT
The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you do not invalidate the session, your app leaks memory until it exits."
Perhaps the delegate is nil on an invalid session (if you always use delegates). Agreed though why is there no isValid call on a session?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With