How does the SwiftUI lifecycle map onto UIKit’s, and what is scenePhase for?

6.2.4 · L2 · Interview

Predict first

Where do you react to the app moving to the background in SwiftUI?

// A: onChange(of: scenePhase) with the .background case
// B: viewDidDisappear
// C: inside body
  • A
  • B
  • C

Mental model. UIKit calls you at each change. SwiftUI hands you a thermometer that you read, and you decide what to do when it crosses a mark.

SwiftUI replaces per-callback methods with observable state. The app declares Scenes (usually a WindowGroup), and the environment value scenePhase reports .active, .inactive or .background for the scene a view is in. You react with .onChange(of: scenePhase), for example to save when it becomes .background. It maps onto the UIKit scene callbacks: .active after did become active, .inactive around will resign active, .background after did enter background. Read it in the App body for the app-wide phase, or in a view for that scene.

Do not confuse view lifetime with app lifecycle. A view’s body is evaluated many times and has no “launch” or “terminate” moment; use .onAppear and .task for view-scoped work (the task is cancelled when the view disappears), @SceneStorage for per-scene state, and @AppStorage for defaults. Process-level events (push registration, background URL sessions) still need @UIApplicationDelegateAdaptor.

scenePhase is the environment value that tracks the scene’s phase. body must stay free of side effects.

Common traps

  • Putting one-time setup in body or onAppear. Both run more than once as the view updates or reappears.
  • Saving on .inactive only. It also happens for a brief interruption; save on .background as well.

They might follow up with

  • How does .task relate to lifecycle? It starts when the view appears and cancels when it disappears, so structured work ends with the view.
  • Is there a SwiftUI “did finish launching”? Use the app’s init, or the delegate adaptor for work that needs the delegate.

Related questions

  • 6.2.1 What are the app states, and which callbacks fire as you move between them?
  • 6.2.2 What is a scene, and what is the split between AppDelegate and SceneDelegate?
  • 6.2.3 What happens inside UIApplicationMain, and how does @main on a SwiftUI App differ?

← What happens inside UIApplicationMain, and how does @main on a…   What does state restoration restore, and how do you make an app… →