Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 896
Spilly Avatar asked Jan 28 '14 19:01

Spilly


2 Answers

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. 
*/
like image 61
ABeanSits Avatar answered Sep 22 '22 11:09

ABeanSits


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?

like image 34
Tom Andersen Avatar answered Sep 22 '22 11:09

Tom Andersen