Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 46 ยท Navigation and App Structure

The App Protocol, Scenes and Scene Phase

Learn how a SwiftUI app starts with @main and the App protocol, how WindowGroup scenes work, and how to react to scenePhase and the app delegate.

Every SwiftUI app has an entry point, and it is not a view. It is a type that conforms to the App protocol. That type describes the scenes of your app, and each scene wraps a root view. Understanding this layer tells you where to create shared objects, how to save data when the app goes to the background, and when you still need a classic app delegate.

All the SwiftUI code in this lesson is read-only, because an iOS app cannot start inside a web page. The runnable examples are stand-ins that model the lifecycle as plain Swift state, so you can see the rules working.

The smallest app

Swift
import SwiftUI

@main
struct HelloApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Three pieces cooperate:

  • @main marks the program entry point. The system creates your App value and runs it. There is no main.swift to write.
  • App has one requirement: a body that returns some Scene.
  • WindowGroup is a scene that shows a window containing your root view. On iPhone there is one window. On iPad and Mac the user can open more of them, each with its own state.

The three layers

App The entry point. Declares the scenes.
Scene One window or instance of the app UI.
View The content inside the scene.

Shared things live in the App, per-window things in the views.

1 / 2

Where shared state is created

The App value lives as long as the process, so it is the right place to own objects that every window shares: a data store, a settings model, a network client. Use @State for an @Observable model (see @Observable and Observation) and put it into the environment:

Swift
@main
struct NotesApp: App {
    @State private var store = NoteStore()

    var body: some Scene {
        WindowGroup {
            NotesList()
                .environment(store)
        }
    }
}

Why @State and not a plain let? An App struct can be re-created by the system. @State keeps the object alive for the lifetime of the app and makes SwiftUI observe it. A plain property would risk creating a second store.

A tempting mistake is to run heavy work in the initializer of the App. Startup time is part of the user experience, and the system can kill an app that is too slow to launch. Create cheap objects up front and load data afterwards, from a view's .task.

Scenes beyond WindowGroup

WindowGroup is the common scene. Others include:

  • Window for a single, unique window (more common on macOS).
  • DocumentGroup for apps built around files the user opens and saves.
  • Settings (macOS) for the preferences window.
  • MenuBarExtra (macOS) for a menu bar item.

An app can declare several scenes, as shown in the previous lesson. On iPhone only the first WindowGroup is shown at launch.

Scene phase

The system moves each scene between three phases. You read the current one from the environment and react to changes with onChange:

Swift
struct RootView: View {
    @Environment(\.scenePhase) private var scenePhase
    @Environment(NoteStore.self) private var store

    var body: some View {
        NotesList()
            .onChange(of: scenePhase) { oldPhase, newPhase in
                switch newPhase {
                case .active:
                    store.refreshIfStale()
                case .inactive:
                    break
                case .background:
                    store.saveNow()
                @unknown default:
                    break
                }
            }
    }
}

What each phase means in practice:

  • active: the scene is in the foreground and the user can interact with it. Refresh data and resume timers or animations.
  • inactive: the scene is visible but not receiving events. This happens briefly during transitions, when the app switcher is open or a system alert covers the screen. Do not treat it as "the user left".
  • background: the scene is not visible. This is your chance to save state. You only get a short time, so write quickly. The system may suspend your process right after and may later terminate it without any further callback.

That last point is the key rule: the system can kill a backgrounded app silently. Never rely on a "will terminate" callback. Save when the phase becomes background (and when the user finishes an edit), not when the app quits.

Where you read scenePhase matters. Read in a view, it reports the phase of that view's scene. Read in the App struct, it reports an aggregate across all scenes (for example, the app is active if any scene is active). Choose per-scene reads for per-window state and the aggregate for app-wide work.

The next two TryIts model the rules with ordinary Swift.

Swift A scene phase state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The legal-transition table here is a simplification that matches what you normally observe: a scene passes through inactive on its way between background and active. Your code should not depend on seeing every step, only on handling each phase correctly.

Swift Saving when the scene goes to the background

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The dirty check is worth copying: background transitions happen often, and rewriting an unchanged file wastes battery and time.

When you still need an app delegate

SwiftUI covers most lifecycle needs, but some system callbacks only exist on the UIKit app delegate: registering for push notifications (the device token callback), handling some background URL session events, and certain third-party SDK setup. You attach a delegate class with an adaptor:

Swift
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        // One-time setup for libraries that insist on it.
        return true
    }
}

@main
struct NotesApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate

    var body: some Scene {
        WindowGroup { ContentView() }
    }
}

Treat the delegate as a small bridge. Keep your logic in SwiftUI-friendly models, and call into them from the delegate methods that cannot be avoided. On macOS the equivalent is @NSApplicationDelegateAdaptor.

The launch screen

Before your first view appears, iOS shows a launch screen: a static placeholder displayed while the app starts. With current Xcode project templates you configure it in the target's Info settings (the UILaunchScreen key in Info.plist), choosing a background color and optionally an image. It is not a splash screen for branding and it cannot run code or show animations.

Two guidelines follow:

  • Make the launch screen look like the first screen of the app (same background, an empty frame of the layout) so the transition feels instant.
  • Do not add a fake delay. If the first screen needs data, show it with a loading state, as the networking lesson will show.

Common mistakes

  • Saving only when the app quits. There is no reliable quit callback. Save on the background phase and after edits.
  • Treating inactive as backgrounded. It also occurs while the app is on screen. Reserve heavy work for active and background.
  • Heavy work in App.init. It delays launch. Load data lazily.
  • Creating the model in body. The body of the App can run again. Own the model with @State.
  • Adding a delegate for things SwiftUI already does, such as reading scene phase or opening URLs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @main do on a SwiftUI App type?

    @main tells the compiler to generate the program's entry point from this type. The system then creates the App value and runs it.
  2. 2. Which scene phase is the right moment to save unsaved work?

    When a scene reaches background the app may be suspended and later killed without a further callback, so saving then is the reliable choice.
  3. 3. Why is an @Observable store in the App struct stored with @State?

    @State owns the object for the lifetime of the app and lets SwiftUI observe it. A plain property could end up creating a second instance.
  4. 4. When do you typically need @UIApplicationDelegateAdaptor?

    SwiftUI covers most needs. The adaptor is a bridge for callbacks that have no SwiftUI equivalent.
  5. 5. What is true about the launch screen?

    The launch screen is a static placeholder configured in the project. It cannot run code, so use a loading state in the first screen instead.

Summary

  • An app starts at a type marked @main that conforms to App and returns scenes from body.
  • WindowGroup shows a root view in a window; iPad and Mac can have several windows.
  • Create shared models in the App with @State and pass them through the environment. Keep startup cheap.
  • scenePhase is active, inactive or background; save work when the phase becomes background.
  • The app can be terminated silently while in the background, so never depend on a quit callback.
  • Use @UIApplicationDelegateAdaptor only for callbacks SwiftUI does not offer.
  • The launch screen is static; show loading states in your own views.

Next: Deep Links and Universal Links