I am using NSURLSessionDownloadTask
objects on an NSURLSession
to allow users to download documents while the app is in the background / device locked. I also want to inform the user that individual downloads have finished through a local notification.
To that end, I am triggering a local notification in the -URLSession:downloadTask:didFinishDownloadingToURL:
download task delegate method, however I am wondering if there might be a better place to add the code triggering a notification, since the way Apple explains it, the download task will be passed to the system, and from that I am deriving that those delegates will not be called anymore on the download task's delegate once (or shortly after) the app is backgrounded.
My question: What is the best place to add the code for triggering the local notifications? Has anybody had any previous experience in adding this sort of a functionality to their application?
Answer on your question can be found in Apple documentation URL Loading System Programming Guide:
In iOS, when a background transfer completes or requires credentials, if your app is no longer running, iOS automatically relaunches your app in the background and calls the
application:handleEventsForBackgroundURLSession:completionHandler:
method on your app’sUIApplicationDelegate
object. This call provides the identifier of the session that caused your app to be launched. Your app should store that completion handler, create a background configuration object with the same identifier, and create a session with that configuration object. The new session is automatically reassociated with ongoing background activity. Later, when the session finishes the last background download task, it sends the session delegate aURLSessionDidFinishEventsForBackgroundURLSession:
message. Your session delegate should then call the stored completion handler.If any task completed while your app was suspended, the delegate’s
URLSession:downloadTask:didFinishDownloadingToURL:
method is then called with the task and the URL for the newly downloaded file associated with it.
As you see it's much more complicated then just set delegate
object. By delegate methods you will be notified only if app in foreground mode. In other cases (app in background mode, app is terminated) you need handle AppDelegate
methods that are described in above quote.
Also Apple provides example project, that shows how to work with background download/upload tasks. This example will help you to find place where to put "Local Notification" code.
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