In what situations will applicationWillTerminate be called? For example, will it ocassionally be called if there is a crash in the code?
Apple's doc is vague on this, it only says when the system needs to terminate it for some reason.
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 when the user quits the app because the app simply moves to the background in that case. However, this method may be called in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.
I have just explored this question (iOS 9.2). And I have got some results.
So, applicationWillTerminate
is called when a user terminates the app without switching it to background mode: the app is active, the user makes double press on Home button and throws out the app.
But if a user switches the app to the background at first, and then after this tries to terminate the app, applicationWillTerminate
will not be called.
You can check this:
- (void)applicationWillTerminate:(UIApplication *)application { [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"term"]; [[NSUserDefaults standardUserDefaults] synchronize]; }
and
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([[NSUserDefaults standardUserDefaults] boolForKey:@"term"]){ [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"term"]; [[NSUserDefaults standardUserDefaults] synchronize]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WORKED" message:@"term works" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; } ... return YES;
}
Starting in iOS 4, the practical answer is "never." (or at least "rarely".) You can't assume that it will ever be called. Normally what happens is that your app gets moved to the background when the user presses the home button and then a few seconds later it shifts to the "suspended state" (Still in memory but not receiving any CPU time.)
Once your app is in the suspended state the system can terminate it at any time without warning (usually due to memory pressure.)
When you are suspended you don't get the applicationWillTerminate call before being killed. You should assume that when you get a applicationDidEnterBackground:
message, you are going to be suspended shortly after, and die while suspended. Get your affairs in order (save app state.)
You may still get calls to your applicationWillTerminate in certain cases, but you should not assume that you will.
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