M-Swift All articles
Swift Architecture

Half a Second of Background Is Still Background: Mapping SwiftUI Scene Phase in the Wild

M-Swift
Half a Second of Background Is Still Background: Mapping SwiftUI Scene Phase in the Wild

Photo: Mictlancihuatl, CC BY-SA 4.0, via Wikimedia Commons

You're three seconds into a 40 MB video upload when the user locks their phone. SwiftUI hands you a scene phase change, you kick off your save routine, and about four seconds later the system suspends the process mid-write. The user unlocks, sees a spinner that never resolves, and leaves a review about "lost progress."

Nothing in that story is exotic. It's the completely standard behavior of an app that treats scenePhase as a boolean — active or not — and never thought hard about the states in between. Let's walk through where that assumption breaks, how to test it on a real iPhone instead of a simulator, and a checklist short enough to actually run before your next release.

Three states, and the one everyone misreads

ScenePhase gives you exactly three values: .active, .inactive, and .background. Most teams write a switch that handles active and lumps everything else into a single default. That's where the trouble starts.

.inactive shows up constantly, and almost always briefly. Pulling Control Center down, holding it there, and letting go generates an inactive → active round trip in well under a second. A notification banner sliding over the top of your UI does it. An incoming call banner does it. The app switcher does it. A system permission alert definitely does it. If your inactive handler flushes caches, tears down a video session, or cancels an in-flight request, you just did it during a UI gesture that ended before the user finished blinking.

.background is the real one. Your process is seconds away from suspension, and you don't control how many seconds. The system decides, and Low Power Mode, memory pressure, and the device's battery age all get a vote.

Treat them differently. Inactive is a hint to pause anything expensive or visual. Background is a deadline.

Where the data actually leaks

State loss rarely comes from not saving. It comes from saving in the wrong place, at the wrong time, with the wrong assumption about how long you'll be allowed to run.

The async save that never lands. You fire a write on .background, it takes six seconds because it's hitting the network or a slow disk, and the system suspends you at four. Wrap anything that must finish in a background task assertion and give yourself an expiration handler that leaves the data in a recoverable state:

@Environment(\.scenePhase) private var scenePhase
@State private var writeTask: UIBackgroundTaskIdentifier = .invalid

.onChange(of: scenePhase) { _, phase in
    guard phase == .background else { return }
    writeTask = UIApplication.shared.beginBackgroundTask(withName: "flush-draft") {
        // Out of time — persist a minimal recovery marker instead.
        store.markDraftDirty()
        UIApplication.shared.endBackgroundTask(writeTask)
        writeTask = .invalid
    }
    Task {
        await store.flush()
        UIApplication.shared.endBackgroundTask(writeTask)
        writeTask = .invalid
    }
}

Timers that assume the clock keeps ticking. A Task.sleep or a Timer pauses when you're suspended, but Date() does not. If you compute elapsed time as Date().timeIntervalSince(start), a user who locks their phone for twenty minutes comes back to a workout timer that claims they ran for twenty minutes. Use a monotonic source — ContinuousClock or DispatchTime — and add the paused interval only for wall-clock presentation.

SwiftData autosave fighting your scene handler. If autosave is on, you're already writing on change notifications. Adding a full flush on every .inactive means two writes per gesture. Pick one owner for persistence and let the other stay quiet.

Sessions that don't restart. AVCaptureSession, AVAudioSession, and ARKit all stop when you background. The bug isn't the stop — it's the missing restart on .active, leaving a black viewfinder or silent playback.

Duplicate work is the quieter bug

Everyone looks for data loss. Fewer people look for the opposite: work that fires twice.

Two .onChange(of: scenePhase) modifiers — one on the root scene, one inside a child view — both call refresh(). Now every time the user peeks at Control Center, you hit the network twice. Do that across a few screens and your API dashboard looks like a DDoS.

One coordinator, one subscription. Something like this is enough:

@Observable
final class SceneCoordinator {
    private var lastResume = Date.distantPast
    private let minimumRefreshGap: TimeInterval = 30

    func sceneBecameActive() {
        guard Date().timeIntervalSince(lastResume) > minimumRefreshGap else { return }
        lastResume = Date()
        Task { await refreshFeed() }
    }
}

That thirty-second floor costs you one line and eliminates an entire category of wasted requests. Tune the number to your data's volatility, not to a feeling.

Test it on a phone, not a simulator

The simulator will happily report scene phase changes, but it won't suspend your process the way a real device does, and it won't reproduce memory-driven kills. Do this on hardware, with os.Logger output streaming to Console.app filtered by your subsystem:

For UI tests, XCUIDevice.shared.press(.home) backgrounds the app reliably and is worth a smoke test. Locking is a simulator-menu affair (Device > Lock), so it's useful for catching handler bugs but not for timing budgets.

A checklist you can run this afternoon

  1. Exactly one .onChange(of: scenePhase) per scene, at the root.
  2. Each phase maps to an intent, not to "save everything."
  3. Async writes during .background are wrapped in a background task with an expiration handler.
  4. Resume work is debounced with a minimum interval.
  5. Elapsed time uses a monotonic clock.
  6. Timers, animations, and camera sessions pause on .background, not .inactive.
  7. Logs verify the full active → inactive → background → inactive → active cycle on a device.
  8. One tested pass in Low Power Mode and one during a phone call.

Don't build a lifecycle framework

There's a temptation, once you notice these bugs, to build a SceneLifecycleManaging protocol with six conformances and a dependency container. Resist it. The whole fix is usually a single file, a coordinator with three methods, and a background task assertion. Scene phase is not a complex subsystem — it's a signal you either listen to carefully or ignore at your own expense.

Start with the log line. Lock the phone. Watch what happens. The gap between what you assumed and what the system actually does is usually wider than you'd like, and it's cheaper to find it now than in a review titled "app loses my notes."

All Articles

Related Articles

Diffing Is Not Mind Reading: A SwiftUI Identity Audit for Lists That Jump

Diffing Is Not Mind Reading: A SwiftUI Identity Audit for Lists That Jump

Your App Group Is a Trust Boundary, Not a Folder

Friendly Fire From Your Network Layer: Auditing Swift Retry Logic Before the Bill Arrives

Friendly Fire From Your Network Layer: Auditing Swift Retry Logic Before the Bill Arrives