applicationWillTerminate when is it called and when not

IphoneIos4

Iphone Problem Overview


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. https://stackoverflow.com/questions/4320557/applicationwillterminate-does-not-get-invoked

Anybody facing the similar issue as me?

Iphone Solutions


Solution 1 - Iphone

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.

Solution 2 - Iphone

I see -applicationWillTerminate: getting called with the following test. In a new project (I used the 'Single View Application' template), add the following to the AppDelegate:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"%s", __PRETTY_FUNCTION__);

    __block UIBackgroundTaskIdentifier identifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        if (identifier != UIBackgroundTaskInvalid) {
            [[UIApplication sharedApplication] endBackgroundTask:identifier];
            identifier = UIBackgroundTaskInvalid;
        }
    }];

    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i=0; i < 20; i++) {
            NSLog(@"%d", i);
            sleep(1);
        }
        if (identifier != UIBackgroundTaskInvalid) {
            [[UIApplication sharedApplication] endBackgroundTask:identifier];
            identifier = UIBackgroundTaskInvalid;
        }
    });
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

This example will start a background task when the app enters the background. The task is just a 20s delay (with logging once a second) that keeps the app running in the background (note the difference between running in the background and suspended) long enough to allow it to be killed from the app switcher.

So, to test it, run the app, hit the home button to send the app to the background, then before the 20s delay is up, remove the app from the app switcher. After the end of the 20s, -applicationWillTerminate: is called. You can watch the console in Xcode to verify that this is the case.

I tried this in the iOS Simulator for iOS 5.1 and 6.1 (both iPhone) and saw it happen in both cases. I also tested on iPhone 4S running iOS 6.1.2 and saw the same behavior.

Solution 3 - Iphone

As I know, there are 3 situations that your application will die.

  1. Terminated by the end user, you can do something in -[UIApplication applicationWillEnterBackground:], in which case, -[UIApplication applicationWillTerminate:] will NOT be called.

  2. Dropped by the system, such as memory not enough, you can do something in -[UIApplication applicationWillTerminate:], in which case, we do NOT know whether applicationWillEnterBackground: has been called;

  3. Crashed, nothing can be done except using some kind of Crash Reporting Tool. (Edited: catching SIGKILL is impossible)

Solution 4 - Iphone

Source: http://www.cocos2d-iphone.org/forum/topic/7386

> I copied my state saving code from applicationWillTerminate to applicationDidEnterBackground and also added a multitaskingEnabled boolean so that I only call state saving in applicationDidEnterBackground. BECAUSE, there is one instance on a multitasking device where applicationWillTerminate is called: If the app is in the foreground and you power off the device. In that case, both applicationDidEnterBackground and applicationWillTerminate get called.

Solution 5 - Iphone

As we know that the App has only 5 sec when -applicationWillTerminate being called. So If someone want to update the server at that point. Than use Synchronous call.

[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&error];

Note:- -applicationWillTerminate will not call if app is being killed from suspended state. Suspended state means app is not working anything in backgroupd. One of the solution for this is to use background task.

Solution 6 - Iphone

Based on Andrew's test, I understand the docs for applicationWillTerminate(_:) to be meant as having the following clarifications:

> For apps that do not support background execution or are linked against iOS 3.x or earlier, this method is always called when the user quits the app. For apps that support background execution, this method is generally not called [right away] when the user quits the app because the app simply moves to the background in that case. However, this method may be called [instead of beginBackgroundTask(expirationHandler:)] in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.

Solution 7 - Iphone

// absolute answer applicationWillTerminate

func applicationWillTerminate(application: UIApplication) {

    print("applicatoinWillTerminate")

    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

step 1: command + shift + h (double click(tab))

step 2: move app top side (kill)

step 3: applicationWillTerminate Work

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnandView Question on Stackoverflow
Solution 1 - IphoneStephen DarlingtonView Answer on Stackoverflow
Solution 2 - IphoneAndrew HershbergerView Answer on Stackoverflow
Solution 3 - IphoneDawnSongView Answer on Stackoverflow
Solution 4 - IphoneJonathon HibbardView Answer on Stackoverflow
Solution 5 - IphoneGagan JoshiView Answer on Stackoverflow
Solution 6 - IphoneEdward BreyView Answer on Stackoverflow
Solution 7 - Iphonegowthaman-mallowView Answer on Stackoverflow