iosnsurlsessionnsurlsessiondownloadtask

Monitoring NSURLSession after app restart


I have a prototype single-view app which monitors download tasks.

enter image description here

I'm trying to deal with following use case:

  1. Downloads are initiated via NSURLSession while app is in foreground. NSURLSession is created with background configuration.
  2. I kill the app with "Xcode Stop", so that app continues download in background. While app is alive, I orderly receive progress callbacks from NSURLSession.
  3. I manually start the app (not by Xcode, but tapping the launch icon), when the downloads have not been completed yet.
  4. I don't receive any URLSession delegate calls for tasks started in previous app's life. The only thing that gets called is handleEventsForBackgroundURLSession but that's called on AppDelegate by the OS (different case than NSURLSession delegate calls).

I want to show progress of ongoing download tasks. Can this be done after app relaunch (when app was terminated by the system, not manually!)?

After app relaunch, NSURLSession is initialized with same identifier, new delegate object, so I figured delegate will continue to receive calls for session's tasks (because session identifier is the same), but apparentely that's not the case. There is a note in Apple's documentation:

The session object keeps a strong reference to the delegate until your app explicitly invalidates the session. If you do not invalidate the session, your app leaks memory.

but I guess this only applies to case when app is alive. When the app is terminated, then all app's objects are gone.


Solution

  • Make sure NSURLSession is properly initialised when app launches. That's what the problem was in my case. I had TransferManager which initialised session as lazy getter which was not getting invoked...

    Now that the NSURLSession is properly initialised, callbacks are fired regularly.

    Stupid error, but there it is.