applicationWillTerminate when is it called and when not

Anand picture Anand · Oct 19, 2011 · Viewed 47.9k times · Source

Hi I have read several questions on SO about applicationWillTerminate getting called and not getting called.

I wanted to summarize what I understood as there are several posts that speak differently.

  1. For IOS (without multitasking) it is called always when home button is pressed.

  2. For IOS 4 and above

    a. it is not called when pressing home button (as the app moves to background)

    b. it is called when closing the app from the multi tasking dock and if the app has a sudden terminate flag in info.plist disabled else it is not called. ( I set the "Application should get App Died events" and even then on closing the app from the multitasking dock the terminate function did not get called)

Based on that I had a couple of questions

Is it a good practise to set the Application should get App Died events flag? ( I set the "Application should get App Died events" and even then on closing the app from the multitasking dock the terminate function did not get called)

or

Is registering for "UIApplicationWillTerminateNotification" a better thing to do than the info.plist setting?

Basically I need to do some work only when the app terminates and NOT when it moves to background.

or

EDIT (1): When the app is terminated the following is sent to the APP. How do I catch it?

Program received signal: “SIGKILL”.

EDIT (2):

Please note : It is not getting called in IOS 4 and above when removing from the multitasking dock. You might think it is. But in my case it is not.

I am asking if anyone knows why? Is there something else I am missing.

Also Note I set the "Application should get App Died events" and even then it is not getting called.

EDIT (3):

The answer for the following question also did not work. applicationWillTerminate does not get invoked

Anybody facing the similar issue as me?

Answer

Stephen Darlington picture Stephen Darlington · Oct 19, 2011

In short, unless you have UIApplicationExitsOnSuspend in your Info.plist set to YES, in iOS4 and above there is no guarantee that applicationWillTerminate: will ever get called.

As the documentation says:

For applications that support background execution, this method is generally not called when the user quits the application because the application simply moves to the background in that case. However, this method may be called in situations where the application is running in the background (not suspended) and the system needs to terminate it for some reason

(Emphasis mine.)

If you need to do something before the app exits you need to do it in applicationDidEnterBackground:. There is no way to catch SIGKILL.