I have a doubt: I have an app with 10 views. I want that, if the user is on View1 and sends the app to the background, it terminates the application (exit (0)). But I wanted this to happen only on View1, on the other screens, if the app goes to the background and then returns, it will continue where it left off. What can I do?
-
1You can check View1 is visible in window's hierarchy in didenterbackground method in Appdelegate , if view is exist u can quit the App. – Sunil M. Jul 24 '17 at 06:41
3 Answers
Apple's guidelines seem to be strictly against terminating your app programmatically (for example, with exit()
); it would go against what iOS users expect of how apps work.
Instead, I recommend the following approach:
When the app is sent to the background (applicationWillResignActive(_:)
is called), check which view controller is currently being displayed.
If it's such that you wish to start over next time the app is brought to the foreground, just reset the app window's root view controller to whatever the initial view controller of your app is (typically, it involves reloading the inital view controller from Main.stroyboard, but your setup could be different).
You can not choose at runtime whether your app goes to the background or is terminated when the user presses the home button ("multitasking"); that is set in stone in your Info.plist file at build time.
Also, remember that even if you are in the screen that you wish to preserve when the user resumes, your app might be terminated by the system while it is in the background (to reclaim scarce system resources), so in that case it will still start from the initial screen. To prevent this, you might want to check out the APIs for state preservation and restoration.

- 16,006
- 8
- 81
- 189
Here is another SO question asking how to find the identity of the current view controller. Why not query the current view when you receive applicationWillResignActive
indicating that your app is going to move to the background and then choose the action you want?

- 12,309
- 6
- 62
- 114
As far as I understand your description Preserving and Restoring State is what you are looking for.
Excerpt from Documentation:
The preservation and restoration process is mostly automatic, but you need to tell iOS which parts of your app to preserve. The steps for preserving your app’s view controllers are as follows:
Required
Assign restoration identifiers to the view controllers whose configuration you want to preserve; see Tagging View Controllers for Preservation.
Tell iOS how to create or locate new view controller objects at launch time; see Restoring View Controllers at Launch Time.
Optional
- For each view controller, store any specific configuration data needed to return that view controller to its original configuration; see Encoding and Decoding Your View Controller’s State.
Here is a link to Preserving Your App’s Visual Appearance Across Launches

- 1
- 1

- 3,910
- 1
- 34
- 46