6.2 · App and scene lifecycle in UIKit and SwiftUI
The most asked platform question at every level: what runs, in what order, and what the system may do to you between events.
Mental model. Since iOS 13 the app is about the process and the scene is about one window of UI. Most lifecycle bugs come from putting a scene’s job in the app’s methods, or the other way round.
States and callbacks
The five states and what runs on each transition.
- What are the app states, and which callbacks fire as you move between them?
An app is always in one of five states. Not running: no process. Inactive: in the foreground but not receiving events (during a system alert, a call overlay… - What is a scene, and what is the split between AppDelegate and SceneDelegate?
A scene (UIScene) is one instance of your app’s UI: a window, or on iPad one of several windows, with its own lifecycle, state and (optionally) its own user…
Entry points
What launches your code, in UIKit and in SwiftUI.
- What happens inside UIApplicationMain, and how does @main on a SwiftUI App differ?
Every UIKit app starts at a main function that calls UIApplicationMain (the @main attribute on the app delegate generates it). It creates the single… - How does the SwiftUI lifecycle map onto UIKit’s, and what is scenePhase for?
SwiftUI replaces per-callback methods with observable state. The app declares Scenes (usually a WindowGroup), and the environment value scenePhase reports…
Surviving termination
Saving and restoring what the user was doing.
- What does state restoration restore, and how do you make an app survive being killed in the background?
The system may terminate a backgrounded app at any time to reclaim memory, and the user will still expect to return to what they were doing. State restoration…
More in iOS platform internals
- 6.1 · The process, the sandbox, entitlements and privacy prompts
- 6.3 · The run loop, its modes, and the main-thread contract
- 6.4 · The launch path: dyld, initialisers and the first frame
- 6.5 · Background modes, BGTaskScheduler and background transfers
- 6.6 · Memory warnings, jetsam and the watchdog
- 6.7 · Info.plist, URL schemes, universal links and associated domains
- 6.8 · App groups, keychain groups and extensions as separate processes
- 6.9 · How a process dies, what it costs, what confines it and what seals it
- 6.10 · Threads and run loops, observers, and what actually runs in a custom mode
- 6.11 · Launch arguments, the scene callbacks, and reading a binary and its plists