ApplicationWillTerminate NSURLSession Possible?
I met exactly the same situation: NSURLSession just does not work in the applicationWillTerminate:
procedure.
But if iOS does not give you 5 seconds to finish your tasks, you can take them by yourself:
sleep (3);
in the end of applicationWillTerminate:
gave me enough time to perform all final network activity. Actually even 1 second delay works fine.
A number of things could be happening:
First, Apple says :"Your implementation of this method has approximately five seconds to perform any tasks and return." Apple Docs
I emphasised "approximately" because taking these 5 seconds for granted is not something that you would normally want to do. This timeout could rely on a number of factors such as the overall availability of resources (impacted by specifics your app has no control over such as other apps running).
Secondly, you say: "although I don't even have a completion handler so it should be executed".
This means that you are executing a synchronous call i.e. a call that has to wait before letting go. Are you sure that zero to approximately 5 seconds is enough for this call? I know it sounds like too much time, but network availability/reliability/speed is also something that we should generally not take for granted.
Did you try doing something else instead of a network call there? Write something to user defaults for example? Put a timer and look for any variations in how much time you are really given.
The issue is not, that 5 seconds (or something like 5 seconds) isn't enough time. And you do not start a task synchronously, because you have no handler. It is still a asynchronous call.
-applicationWillTerminate:
is send on shut-down of the app. When it returns, the app is shot-down, even there are additional background tasks. So the background task is stopped, too. Therefore the background task only has milliseconds or less to finish.
You could use a synchronous request, so -applicationWillTerminate:
does not return, before the request is done. However, this is never a got idea and for sure not in -applicationWillTerminate:
. If you want to tell the server, that the app is gone, simply implement a heart beat. This has the additional advantage, that apps that quits without sending -applicationWillTerminate:
are unregistered, too. (I. e. in case of crash.)