Proper way to exit iPhone application?
Asked Answered
S

24

293

I am programming an iPhone app, and I need to force it to exit due to certain user actions. After cleaning up memory the app allocated, what's the appropriate method to call to terminate the application?

Smack answered 10/12, 2008 at 5:42 Comment(9)
There is only one proper way - Home button..Befuddle
The only situation I can imagine anyone considering to quit programmatically is the following scenario: App starts, displays terms of use, refusing to accept then quits the app. This is something brands sometimes pressure the developer to do. But it is wrong.Phraseograph
@Phraseograph Normally you put your disclaimer/terms of use (EULA) on itunes connect when you upload the app. If the user downloads your app it means they have accepted your EULAAntigua
even hitting the home button doesnt quit the app technically, the app only goes in the background.. right??Envelope
If someone is searching for this, and can use Private APIs, see this answer.Captain
I don't understand why you would even need to quit the app. Even for something like the EULA within the app, just don't go to next page of the app until user taps the "accept Terms & Conditions" button, so they keep staring at the same page until they accept. Or do you want the comic answer ? Hasta la vista, baby!Chrystel
@Phraseograph it's not only wrong, if the user can't use your app in any way if you don't agree to their EULA or fail any other conditions, Apple will simply not approve such an app. This happened to an app that required an active Internet connection to launch/use.Aneto
There are completely valid reasons for needing to force quit an ios app. My case is that I'm distributing pre-launch beta versions of my app. The beta versions open up all the IAP's for free. These have a time limit and need to expire after a few weeks. So I'm using the answer below to kill the app after the beta period is over. I'll remove this in the LIVE version. But still the answer helped me and is correct!Laddie
One valid reason to quit an app is if it is a long-lived background executing app, and the app enters a state where it no longer needs to run in the background. For example, the user logs out. In this case it would make sense to exit so that when the app next starts it starts clean. This would act as a safety net against memory leaks, among other reasons. Note, in this case the app would be exiting out of the background, so the user would not notice anything wrong.Azole
B
226

Have you tried exit(0)?

Alternatively, [[NSThread mainThread] exit], although I have not tried that it seems like the more appropriate solution.

Biogeography answered 10/12, 2008 at 5:49 Comment(22)
As doing this is an Apple no-no (may cause your app to be refused in the app-store for non-standard interface), consider August's answer as "the right one." FYI, this answer (Brett's) is correct for ALL C programs, and NSThread for all Cocoa programs.Glyceryl
In Tech Q&A QA1561, Apple strongly discourages use of exit as it makes the app appear to have crashed. developer.apple.com/iphone/library/qa/qa2008/qa1561.htmlNari
[[NSThread mainThread] exit] causes your application to crash, because exit is not an instance method. exit(0) will send the app to the background in iOS 4. Calling exit(0) again will crash it. At least in the simulator.Belcher
I have an app which should only be run continuously in the background (closely monitoring location) under certain circumstances, and it will drain the battery very fast otherwise. Turning off the GPS and all client-server communications don't seem to improve battery life when the app is in the background, so it seems like in my case exit(0); is the only option. In fact, under iOS4 the behavior will look identical to the user - app still goes to quick-launch area.Carbazole
Also, I've seen apps on the App Store that already do this. So, you could probably get past the reviewers. But, it's still a risk.Duckweed
-1 Not sure why this answer is voted up so much; exit(0) is very much against Apple's advice. See developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/…Jacob
I use this for development only, but exit(0) keeps the icon in the application tray (iOS4+), eventhough the app is not running anymore.Guttering
Zynga's Words With Friends does this, and it's really awful. I've complained to the developers but they don't listen. Can I report them to Apple? I know it sounds nasty to do so, but they need to be made aware that this is wrong!Bitthia
more understandable is to use it like this: exit(EXIT_SUCCESS);Kaiak
I understand why so many people are advising against this, but how about giving us developers some credit? We're all adults here, and we want to know about this feature. I find it very useful for internal QA builds and, when I first searched for it, was glad to see this "incorrect" answer.Chuppah
I know this is old but I can't believe this has been accepted as the correct answer. This is so wrong. -1Barby
There are cases where you would want to do this - for example if an evil developer copies your bundle and reskins your app and submits to the store you could check for a list of allowed bundle id's and exit the application if the bundle id is not valid.Bryantbryanty
PsychoDad: I'd suggest making your apps cooler instead of worrying about pirates and copycats. They'll find ways to break your systems anyway. And the measures that you suggest might backfire and when that happens you are history.Leisured
@GlennMaynard How is it correct though? The Op asked for a "proper way" to exit an iOS application, since there is no proper way (Apple doesn't want you to kill your app), the only correct answer is "don't do that".Elizbeth
@Elizbeth "Don't do that" is never the correct answer. Give warnings and disclaimers if you like, but the only correct answer to "how do I do this" is "here's how to do it". If I'm searching for how to do something (maybe I want to force it to exit while debugging), people righteously declaring "you don't!" and trying to bury the answer I need is a waste of my time. However many people might have bad reasons to do something, the correct StackOverflow answer is the one that answers the question, because people with good reasons will search their way to it as well.Teratology
@GlennMaynard That may be, but the voting system exists to filter out stupid shit and bad practises from quality content that future SO users can use as well, not to find you an answer to your edge-case that is never going to be used be someone else. Hence the "too localised" flag on questions.Elizbeth
@Elizbeth No, votes on answers aren't a way to say you don't like the question. The voting system doesn't exist to filter out correct answers, regardless of whether the question is often a bad idea or not. People downvoting answers because they actually answer the question is just silly, and something isn't an "edge case" or "too localized" just because you didn't think of it. At least in this case, averages won out.Teratology
@GlennMaynard I believe if the question is "how to do x properly" and "x" is not something you should do, then it's a bad question and it has no correct answer. You can't do something properly that you shouldn't do at all, answers that still try to answer it are clutter and they encourage people to do things they shouldn't do. You might use the answer responsibly because you are aware it shouldn't be used in production, but future readers might not. I think ensuring quality for both the OP and future readers is more important than solving a single user's problem, that is likely an edge-case.Elizbeth
@GlennMaynard "Properly" is an important keyword here.Elizbeth
@Elizbeth No, it's irrelevant. (No question is asking "what's the wrong way to do this".)Teratology
Core data is leaking memory big time, so in my case I have to do the initial import (24 tables, 50 MB json in total) in phases and exit in between each step. (is an enterprise app so app store review is not a concern)Hadhramaut
In addition to @Nari comment. The working link: developer.apple.com/library/archive/qa/qa1561/_index.htmlOverstretch
P
276

On the iPhone there is no concept of quitting an app. The only action that should cause an app to quit is touching the Home button on the phone, and that's not something developers have access to.

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

Piles answered 10/12, 2008 at 14:54 Comment(21)
Even if the user has pushed an exit button in the app and confirmed their selection?Smack
As I said, it's non-standard behavior and should be avoided. iPhone apps are not desktop apps. Don't treat them as such.Piles
If you plan to submit your app to the AppStore, you may get a note from ITC saying that an "exit button" is non-standard interface. That's what the big button below the screen is for :)Glyceryl
I can understand Apples opinion but I have a similar situation, my application requires internet access, if it isn't available they should be able to leave the app instead of just having an error messagePeritonitis
No, not really. Think of the iTunes app. If it doesn't find a connection it tells you. You then navigate away from the app to close it.Piles
We have apps that helps people sleep. They want the app to terminate after a set period to reduce battery drain. I think this case is acceptable - as the user is hopefully asleep and can't exit the app manually.Amalle
I'd still disagree. When they wake up, the app is "gone" leaving the user to wonder what happened. Instead, set a timer in your app, then when the time is up, idle the app -- no activity. An app doing absolutely nothing won't drain the battery.The Springboard is an app, too -- it doesn't shut down just to save energy. Instead, it simply waits for user input.Piles
I'm making an exit button to deal with the case when we are unable to initialize the phone on first launch. If there is insufficient free space, I can't build the database I need and the user can't use the app. I can't call applicationWillTerminate because that does lots of work for normal shutdowns and I think it's an ugly hack to instruct the user to push the home button.Sexagenarian
My client wants to show a minimal EULA in a UIAlertView upon first launch (with Decline / Accept options). If they decline, the app is to shut down immediately. Otherwise, it proceeds. They only see this once, after installation. What about then? Is it still non-standard?Fourflusher
@KiwiBastard: The proper way to handle this situation is to turn off the idle timer so that the device doesn't turn itself off and your app continues to run. When your app's internal timer expires, re-enable the idle timer and let the device turn itself off.Sordello
@jdandrea: Customers have already implicitly accepted Apple's standard EULA or your clients' substitute EULA. I'd expect a rejection from Apple with a EULA dialog at app start-up.Sordello
@jdandrea Is this app a free app? If not, how do you return the money to those users who reject the "minimal EULA"?Praedial
This doesn't really answer the question. It's 100% accurate, but I think ideally would have been a comment either on the OP's question or on the accepted answer.Wagon
@quixoto It does answer the question. The answer to this question is "there isn't one".Antichlor
I know Apple doesn't want you to quit your app, but since iOS4 "multi taksing" it can be annoying to leave apps running. So what if I make a setting that lets users choose if the app should quit or not (it's a game, and nothing is lost when its quit) and let it default to off (not quitting)? BTW, the different answers suggesting that exit(0); should work: the app does quit, but its icon stays in the application tray. Not good!Guttering
@Guttering - Late answer, but leaving the icon in the application tray is expected behavior from an iOS app. Even if it reinitializes when switching back to it (which I find highly annoying), the tray should contain everything I've used lately.Iraqi
The aim of any app developer should be to have an app that is user friendly, not user hostile. One of the key rules of that is to fit in with their expectations. That's why platforms have UI standards, official or de-facto. The iOS standard is that apps don't ever quit when they are in the foreground. No ifs, no buts, no special cases. Your app consumes too much power when it's running? Fix it. You need an EULA? No you don't. You don't have enough memory to run? Display an error, with a try-again button, so the user can switch apps or use iTunes to fix the problem, then come back. etc.Blakey
I have an app that gets pushed to users' iPads from a government client. Since users don't download this app from the Apple app store, there is no chance for them to read the EULA before opening the app itself, and we have to show them the EULA immediately on the first time they open the app. Most of our users are not particularly tech-savvy, and if the app doesn't close when they click "Decline", they get confused.Turanian
Old question, I know, but for clarity: "I'd expect a rejection from Apple with a EULA dialog at app start-up" <- Not true. We present a EULA agreement VC on app start-up and have been through at least 15 reviews (updates) without a rejection. We do NOT however exit() on disagree. If the user doesn't agree to the EULA that's all they can see from the app until they agree.Burger
The question does not ask for advice on best practises, but for a technical answer. Perhaps the OP has a very good reason to want to do this, which you simply do not know.Ludeman
I have an app which only purpose is to open a website then it should close. I need to solve it that way, because the webview is bugged and you cannot download pdf for exampleImmersion
B
226

Have you tried exit(0)?

Alternatively, [[NSThread mainThread] exit], although I have not tried that it seems like the more appropriate solution.

Biogeography answered 10/12, 2008 at 5:49 Comment(22)
As doing this is an Apple no-no (may cause your app to be refused in the app-store for non-standard interface), consider August's answer as "the right one." FYI, this answer (Brett's) is correct for ALL C programs, and NSThread for all Cocoa programs.Glyceryl
In Tech Q&A QA1561, Apple strongly discourages use of exit as it makes the app appear to have crashed. developer.apple.com/iphone/library/qa/qa2008/qa1561.htmlNari
[[NSThread mainThread] exit] causes your application to crash, because exit is not an instance method. exit(0) will send the app to the background in iOS 4. Calling exit(0) again will crash it. At least in the simulator.Belcher
I have an app which should only be run continuously in the background (closely monitoring location) under certain circumstances, and it will drain the battery very fast otherwise. Turning off the GPS and all client-server communications don't seem to improve battery life when the app is in the background, so it seems like in my case exit(0); is the only option. In fact, under iOS4 the behavior will look identical to the user - app still goes to quick-launch area.Carbazole
Also, I've seen apps on the App Store that already do this. So, you could probably get past the reviewers. But, it's still a risk.Duckweed
-1 Not sure why this answer is voted up so much; exit(0) is very much against Apple's advice. See developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/…Jacob
I use this for development only, but exit(0) keeps the icon in the application tray (iOS4+), eventhough the app is not running anymore.Guttering
Zynga's Words With Friends does this, and it's really awful. I've complained to the developers but they don't listen. Can I report them to Apple? I know it sounds nasty to do so, but they need to be made aware that this is wrong!Bitthia
more understandable is to use it like this: exit(EXIT_SUCCESS);Kaiak
I understand why so many people are advising against this, but how about giving us developers some credit? We're all adults here, and we want to know about this feature. I find it very useful for internal QA builds and, when I first searched for it, was glad to see this "incorrect" answer.Chuppah
I know this is old but I can't believe this has been accepted as the correct answer. This is so wrong. -1Barby
There are cases where you would want to do this - for example if an evil developer copies your bundle and reskins your app and submits to the store you could check for a list of allowed bundle id's and exit the application if the bundle id is not valid.Bryantbryanty
PsychoDad: I'd suggest making your apps cooler instead of worrying about pirates and copycats. They'll find ways to break your systems anyway. And the measures that you suggest might backfire and when that happens you are history.Leisured
@GlennMaynard How is it correct though? The Op asked for a "proper way" to exit an iOS application, since there is no proper way (Apple doesn't want you to kill your app), the only correct answer is "don't do that".Elizbeth
@Elizbeth "Don't do that" is never the correct answer. Give warnings and disclaimers if you like, but the only correct answer to "how do I do this" is "here's how to do it". If I'm searching for how to do something (maybe I want to force it to exit while debugging), people righteously declaring "you don't!" and trying to bury the answer I need is a waste of my time. However many people might have bad reasons to do something, the correct StackOverflow answer is the one that answers the question, because people with good reasons will search their way to it as well.Teratology
@GlennMaynard That may be, but the voting system exists to filter out stupid shit and bad practises from quality content that future SO users can use as well, not to find you an answer to your edge-case that is never going to be used be someone else. Hence the "too localised" flag on questions.Elizbeth
@Elizbeth No, votes on answers aren't a way to say you don't like the question. The voting system doesn't exist to filter out correct answers, regardless of whether the question is often a bad idea or not. People downvoting answers because they actually answer the question is just silly, and something isn't an "edge case" or "too localized" just because you didn't think of it. At least in this case, averages won out.Teratology
@GlennMaynard I believe if the question is "how to do x properly" and "x" is not something you should do, then it's a bad question and it has no correct answer. You can't do something properly that you shouldn't do at all, answers that still try to answer it are clutter and they encourage people to do things they shouldn't do. You might use the answer responsibly because you are aware it shouldn't be used in production, but future readers might not. I think ensuring quality for both the OP and future readers is more important than solving a single user's problem, that is likely an edge-case.Elizbeth
@GlennMaynard "Properly" is an important keyword here.Elizbeth
@Elizbeth No, it's irrelevant. (No question is asking "what's the wrong way to do this".)Teratology
Core data is leaking memory big time, so in my case I have to do the initial import (24 tables, 50 MB json in total) in phases and exit in between each step. (is an enterprise app so app store review is not a concern)Hadhramaut
In addition to @Nari comment. The working link: developer.apple.com/library/archive/qa/qa1561/_index.htmlOverstretch
C
52

exit(0) appears to a user as crashes, so show a confirmation message to user. After confirmation suspend (home button press programmatically) and wait 2 seconds while app is going background with animation then exit behind user's view

-(IBAction)doExit
{
    //show confirmation message to user
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                 message:@"Do you want to exit?"
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:@"OK", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != 0)  // 0 == the cancel button
    {
        //home button press programmatically
        UIApplication *app = [UIApplication sharedApplication];
        [app performSelector:@selector(suspend)];
    
        //wait 2 seconds while app is going background
        [NSThread sleepForTimeInterval:2.0];
    
        //exit app when app is in background
        exit(0);
    }
}
Csch answered 23/7, 2013 at 5:54 Comment(2)
Will apple approve this "exit(0)" ? Because some people says apple will reject your app when you use exit 0.Chromoprotein
@GajendraKChauhan exit(0) doesn't matter. Point is your app has "quitting behaviour". Quitting behaviour itself is prohibited in AppStore except a few apps that are made by very important 3rd-parties. Also, imitating home button behaviour is also subject to be rejected.Baber
H
41

Check the Q&A here: https://developer.apple.com/library/content/qa/qa1561/_index.html

Q: How do I programmatically quit my iOS application?

There is no API provided for gracefully terminating an iOS application.

In iOS, the user presses the Home button to close applications. Should your application have conditions in which it cannot provide its intended function, the recommended approach is to display an alert for the user that indicates the nature of the problem and possible actions the user could take — turning on WiFi, enabling Location Services, etc. Allow the user to terminate the application at their own discretion.

WARNING: Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen.

Additionally, data may not be saved, because -applicationWillTerminate: and similar UIApplicationDelegate methods will not be invoked if you call exit.

If during development or testing it is necessary to terminate your application, the abort function, or assert macro is recommended

Holmberg answered 5/6, 2010 at 14:31 Comment(2)
Just added an AlertView without buttons to comply with this. Easy.Inexpensive
Great answer, just worked with exit(0) and didn't know it belongs to the private apiHeriberto
F
38

Its not really a way to quit the program, but a way to force people to quit.

UIAlertView *anAlert = [[UIAlertView alloc] initWithTitle:@"Hit Home Button to Exit" message:@"Tell em why they're quiting" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[anAlert show];
Fallal answered 4/8, 2009 at 0:59 Comment(4)
At least on the simulator, if you do this, the alert will still be there when the user re-opens the app. Thus, I suggest giving them at least one button.Beaudette
Use Kalyan's answer so that app quits when home button is pressed.Palaeo
The problem with this is that it doesn't actually exit the app, so anything the developer might want to accomplish by exiting (throwing out invalid/old UI, clearing constants, etc.) won't be performed unless the user swipes the application closed.Pyorrhea
This doesn't kill the app.Brooke
T
37

Go to your info.plist and check the key "Application does not run in background". This time when the user clicks the home button, the application exits completely.

Thursby answered 1/6, 2011 at 4:47 Comment(1)
But background process also get dismiss.Chromoprotein
B
17

Add UIApplicationExitsOnSuspend property on application-info.plist to true.

Bratislava answered 7/7, 2011 at 8:14 Comment(1)
Can this setting be changed in run-time? I mean, I want to live in the background, except when my app CHOOSES to quit on the next suspend - in which time I'll want to introduce the UIApplicationExitsOnSuspend. Is this possible?Aikido
G
13

After some tests, I can say the following:

  • using the private interface : [UIApplication sharedApplication] will cause the app looking like it crashed, BUT it will call - (void)applicationWillTerminate:(UIApplication *)application before doing so;
  • using exit(0); will also terminate the application, but it will look "normal" (the springboard's icons appears like expected, with the zoom out effect), BUT it won't call the - (void)applicationWillTerminate:(UIApplication *)application delegate method.

My advice:

  1. Manually call the - (void)applicationWillTerminate:(UIApplication *)application on the delegate.
  2. Call exit(0);.
Giacometti answered 17/5, 2009 at 17:0 Comment(1)
Apple says not to use exit due to "Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen" developer.apple.com/library/ios/#qa/qa2008/qa1561.htmlBelayneh
C
9

Your ApplicationDelegate gets notified of intentional quitting by the user:

- (void)applicationWillResignActive:(UIApplication *)application {

When I get this notification I just call

        exit(0);

Which does all the work. And the best thing is, it is the useres intent to quit, which is why this should not be a problem calling it there.

On my Audio-App it was necessary to quit the app after people were syncing their device while the music was still playing. As soon as the syncing is complete I get a notification. But quitting the app right after that would actually look like a crash.

So instead I set a flag to REALLY quit the app on the next backgrounding action. Which is okay for refreshing the app after a sync.

Camera answered 12/8, 2010 at 10:41 Comment(2)
This is not a good solution as the application will resign active for other reasons, such as incoming phone call.Azole
The solution is to add a check that exits only if it is useful to do so. For example if the user is on the start screen. Then it is ok even if a phonecall is coming in. Apple has not rejected this since iOS 2 in my apps. https://mcmap.net/q/102111/-force-iphone-app-to-restart-programmaticallySprage
E
6

My App has been rejected recently bc I've used an undocumented method. Literally:

"Unfortunately it cannot be added to the App Store because it is using a private API. Use of non-public APIs, which as outlined in the iPhone Developer Program License Agreement section 3.3.1 is prohibited:

"3.3.1 Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs."

The non-public API that is included in your application is terminateWithSuccess"

Emelyemelyne answered 2/12, 2009 at 17:44 Comment(0)
C
6

Apple say:

"Warning: Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen."

I think that this is a bad assumption. If the user tap a quit button and a message appears that say something like: "The application will now quit.", it doesn't appear to be crashed. Apple should provide a valid way to quit an application (not exit(0)).

Corpsman answered 23/5, 2013 at 12:1 Comment(1)
They do it's call the Home button it can be located at the bottom of any iDevice. So because of this there is never any need to build your own quit button in.Barby
C
5

You should not directly call the function exit(0) as it will quit the application immediately and will look like your app is crashed. So better to show users a confirmation alert and let them do this themselves.

Swift 4.2

func askForQuit(_ completion:@escaping (_ canQuit: Bool) -> Void) {
    let alert = UIAlertController(title: "Confirmation!", message: "Do you want to quit the application", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: { (action) in
        alert.dismiss(animated: true, completion: nil)
        completion(true)
    }))
    alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: { (action) in
        alert.dismiss(animated: true, completion: nil)
        completion(false)
    }))
    self.present(alert, animated: true, completion: nil)
}

/// Will quit the application with animation
func quit() {
    UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
    /// Sleep for a while to let the app goes in background
    sleep(2)
    exit(0)
}

Usage:

self.askForQuit { (canQuit) in
     if canQuit {
         self.quit()
     }
}
Cumber answered 18/6, 2019 at 10:7 Comment(0)
C
4

This has gotten a good answer but decided to expand a bit:

You can't get your application accepted to AppStore without reading Apple's iOS Human Interface Guidelines well. (they retain the right to reject you for doing anything against them) The section "Don't Quit Programmatically" http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/UEBestPractices/UEBestPractices.html is an exact guideline in how you should treat in this case.

If you ever have a problem with Apple platform you can't easily find a solution for, consult HIG. It's possible Apple simply doesn't want you to do it and they usually (I'm not Apple so I can't guarantee always) do say so in their documentation.

Camilia answered 3/2, 2011 at 15:23 Comment(0)
D
3

Hm, you may 'have to' quit the application if, say, your application requires an internet connection. You could display an alert and then do something like this:

if ([[UIApplication sharedApplication] respondsToSelector:@selector(terminate)]) {
    [[UIApplication sharedApplication] performSelector:@selector(terminate)];
} else {
    kill(getpid(), SIGINT); 
}
Duello answered 11/12, 2008 at 1:55 Comment(2)
No, you don't have to terminate it. The iTunes app, for example, when it can't detect a proper connection simply puts up a screen that says they're not connected. It doesn't quit, it simply informs the user of what's going on. The user then quits by tapping the home button.Piles
The compass app quits if it's unable to function, though.Forspent
P
3

We can not quit app using exit(0), abort() functions, as Apple strongly discourage the use of these functions. Though you can use this functions for development or testing purpose.

If during development or testing it is necessary to terminate your application, the abort function, or assert macro is recommended

Please find this Apple Q&A thread to get more information.

As use of this function create impression like application is crashing. So i got some suggestion like we can display Alert with termination message to aware user about closing the app, due to unavailability of certain functionality.

But iOS Human Interface Guideline for Starting And Stopping App, suggesting that Never use Quit or Close button to terminate Application. Rather then that they are suggesting to display proper message to explain situation.

An iOS app never displays a Close or Quit option. People stop using an app when they switch to another app, return to the Home screen, or put their devices in sleep mode.

Never quit an iOS app programmatically. People tend to interpret this as a crash. If something prevents your app from functioning as intended, you need to tell users about the situation and explain what they can do about it.

Phillip answered 28/4, 2016 at 13:21 Comment(0)
C
2

In addition to the above, good, answer I just wanted to add, think about cleaning up your memory.

After your application exits, the iPhone OS will automatically clean up anything your application left behind, so freeing all memory manually can just increase the amount of time it takes your application to exit.

Cordiacordial answered 10/12, 2008 at 14:4 Comment(1)
Please modify your answer in current scenario of IOS4.0 and UP.. :PAnguilliform
J
2
- (IBAction)logOutButton:(id)sender
{
   //show confirmation message to user
   CustomAlert* alert = [[CustomAlert alloc] initWithTitle:@"Confirmation" message:@"Do you want  to exit?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
   alert.style = AlertStyleWhite;
   [alert setFontName:@"Helvetica" fontColor:[UIColor blackColor] fontShadowColor:[UIColor clearColor]];
   [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

   if (buttonIndex != 0)  // 0 == the cancel button
   {
      //home button press programmatically
      UIApplication *app = [UIApplication sharedApplication];
      [app performSelector:@selector(suspend)];
      //wait 2 seconds while app is going background
      [NSThread sleepForTimeInterval:2.0];
      //exit app when app is in background
      NSLog(@"exit(0)");
      exit(0);
  }
}
Junitajunius answered 17/9, 2013 at 11:56 Comment(0)
E
1
[[UIApplication sharedApplication] terminateWithSuccess];

It worked fine and automatically calls

- (void)applicationWillTerminateUIApplication *)application delegate.

to remove compile time warning add this code

@interface UIApplication(MyExtras)
  - (void)terminateWithSuccess;
@end 
Elyot answered 5/11, 2009 at 15:1 Comment(5)
This is a private method, Diego Mercado has explained above that his app got rejected, then why take such a risk.Lianneliao
Use private API will get the app rejected by Apple.Etherealize
for enterprise app - this can be a solution.Kodiak
- (IBAction)exitApp:(id)sender { SEL selector = NSSelectorFromString(@"terminateWithSuccess"); [self performSelector:selector withObject:[UIApplication sharedApplication]]; }Bushelman
@unmircea did that pass review?Nowak
N
1

I used the [[NSMutableArray new] addObject:nil] approach mentioned above to force-quit (crash) the app without making a tell-tale exit(0) function call.

Why? Because my app uses certificate pinning on all network API calls to prevent man-in-the-middle attacks. These include the initialization calls my financial app makes on startup.

If certificate authentication fails, all of my initialization calls error out and leave my app in an indeterminate state. Letting the user go home and then back into the app doesn't help, as unless the app has been purged by the OS it's still uninitialized and untrustworthy.

So, in this one case, we deemed it best to pop an alert informing the user that the app is operating in an insecure environment and then, when they hit "Close", force quit the app using the aforementioned method.

Ninetieth answered 24/11, 2015 at 23:44 Comment(3)
I can't see what holds you from displaying a single full-screen mundane alert, telling the user that the app isn't usable for those "certificate pinning" reasons, and that's it. User will eventually close the app. You may not know, but iOS reserves the right to kill your process (maintaining its state) and restoring it later, and the "life-cycle" of iOS application isn't really in your hands. Your crash - is simply a crash, and the OS may choose to revive the app anyway.Aikido
Wow, three year old post. Anyway, the new app architecture pretty much does that, with a retry button that retries the API and either drops the block screen, or returns them to the block screen with a new error.Ninetieth
The old app structure pretty much didn't allow any good way to retry the startup API calls and the app was in an inconsistent state without them. We could have used a permanent block screen, but that required the user to force-quit the app himself and it was decided that not every user knew HOW to double-click and force quit apps. Easier today, but quite hidden three years ago.Ninetieth
L
0

The user should decide when an app exits. I don't think it is a good user interaction when an app quits. Therefore there is no nice API for it, only the home button has one.

If there is an error: Implement it better or Notify the user. If there have to be a restart: Implement it better of Notify the user.

It sounds dumb, but it's bad practice to exit the app without letting the user decide and not notifying him. And since there is a home button for the user interaction, Apple states, there should not be 2 things for the same function (exiting an app).

Liminal answered 30/9, 2013 at 9:53 Comment(0)
M
0

Exit an app other way than the home button is really non-iOS-esque approach.

I did this helper, though, that use no private stuff:

void crash()
{ [[NSMutableArray new] addObject:NSStringFromClass(nil)]; }

But still not meant for production in my case. It is for testing crash reportings, or to fast restart after a Core Data reset. Just made it safe not to be rejected if function left in the production code.

Malachi answered 27/1, 2014 at 14:57 Comment(0)
A
0

It may be appropriate to exit an app if it is a long lived app that also executes in the background, for example to get location updates (using the location updates background capability for that).

For example, let's say the user logs out of your location based app, and pushes the app to the background using the home button. In this case your app may keep running, but it could make sense to completely exit it. It would be good for the user (releases memory and other resources that don't need to be used), and good for app stability (i.e. making sure the app is periodically restarted when possible is a safety net against memory leaks and other low memory issues).

This could (though probably shouldn't, see below :-) be achieved with something like:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if (/* logged out */) {
        exit(0);
    } else {
       // normal handling.
    }
}

Since the app would then exit out of the background it will not look wrong to the user, and will not resemble a crash, providing the user interface is restored the next time they run the app. In other words, to the user it would not look any different to a system initiated termination of the app when the app is in the background.

Still, it would be preferable to use a more standard approach to let the system know that the app can be terminated. For example in this case, by making sure the GPS is not in use by stopping requesting location updates, including turning off show current location on a map view if present. That way the system will take care of terminating the app a few minutes (i.e. [[UIApplication sharedApplication] backgroundTimeRemaining]) after the app enters the background. This would get all the same benefits without having to use code to terminate the app.

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if (/* logged out */) {
       // stop requesting location updates if not already done so
       // tidy up as app will soon be terminated (run a background task using beginBackgroundTaskWithExpirationHandler if needed).
    } else {
       // normal handling.
    }
}

And of course, using exit(0) would never be appropriate for the average production app that runs in the foreground, as per other answers that reference http://developer.apple.com/iphone/library/qa/qa2008/qa1561.html

Azole answered 12/10, 2015 at 16:55 Comment(0)
K
0

Swift 4.2 (or older)

Library called Darvin can be used.

import Darwin

exit(0) // Here you go

NB: This is not recomanded in iOS applications.

Doing this will get you crash log.

Kellda answered 28/2, 2019 at 9:51 Comment(0)
M
0

In iPadOS 13 you can now close all scene sessions like this:

for session in UIApplication.shared.openSessions {
    UIApplication.shared.requestSceneSessionDestruction(session, options: nil, errorHandler: nil)
}

This will call applicationWillTerminate(_ application: UIApplication) on your app delegate and terminate the app in the end.

But beware of two things:

More info about scenes in iOS/iPadOS 13: https://developer.apple.com/documentation/uikit/app_and_environment/scenes

Maxey answered 21/11, 2019 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.