download

Why does iOS lose unsaved form data without calling willTerminate?

Mobile~8 minReviewed 2 Dec 2026Free · No sign-in

Question

An iOS expense app keeps an unsaved receipt in memory and writes it to disk inside applicationWillTerminate(_:). Users switch to Mail, return twenty minutes later, and their receipt is gone.

A colleague moves the save into sceneDidEnterBackground(_:) and calls beginBackgroundTask to upload the receipt, without calling endBackgroundTask(_:) in the expiration handler. Now crash logs report watchdog kills (0x8badf00d) in the background.

  1. Trace the iOS lifecycle states after switching to Mail, and explain why applicationWillTerminate(_:) never ran.
  2. How do you persist state reliably and use beginBackgroundTask safely?
Show hints (3)
  1. "WHAT HAPPENS WHEN SUSPENDED"

    After entering the background, iOS freezes your app in the Suspended state. Does iOS wake a frozen process before reclaiming its memory?

  2. "PERSIST BEFORE FREEZING"

    Save critical user edits incrementally, or at the latest inside sceneDidEnterBackground(_:) or SwiftUI ScenePhase.background.

  3. "BALANCE EVERY BACKGROUND TASK"

    beginBackgroundTask grants only a short finite window. Every non-.invalid ID must call endBackgroundTask(_:) on completion and on expiration.

Show checked explanation

Switching apps moves the scene through Active, Inactive, Background, and then Suspended. iOS purges suspended apps under memory pressure without waking them or calling applicationWillTerminate(_:). Save critical state incrementally or in sceneDidEnterBackground(_:) (ScenePhase.background). Always pair beginBackgroundTask with endBackgroundTask(_:) on both normal completion and inside the expiration handler.

Scene state transitions, silent suspended termination, and beginBackgroundTask expiration balancing were checked in a Python 3.12 state model against iOS 18 UIKit and SwiftUI documentation. Checked by an editor other than the author.

Walkthrough

Each iOS scene moves through five lifecycle states, and your code only gets CPU time in three of them:

statevisible on screenCPU runswhat your app should do
Activeyesyesrun UI, timers, and user interactions
Inactivepartial or transitioningyespause gameplay or live timers
Backgroundnobrieflysave critical data and release heavy caches
Suspendednonofrozen in RAM; iOS may purge silently
Terminatednonoprocess removed from memory

When the user switches to Mail, the scene passes through Inactive into Background, finishes its brief callback, and freezes in Suspended. Twenty minutes later, iOS needs RAM and kills the suspended process directly. Because the process is frozen, applicationWillTerminate(_:) never runs, and any memory-only receipt vanishes.

To protect user work, write critical changes locally as the user edits, or flush them inside sceneDidEnterBackground(_:) (in UIKit) or .onChange(of: scenePhase) when newPhase == .background (in SwiftUI).

If you need a few extra seconds to finish a short write or API commit, call UIApplication.shared.beginBackgroundTask(withName:expirationHandler:). iOS grants a short, system-controlled window (often around 30 seconds, never guaranteed). If you fail to call endBackgroundTask(_:) when that window expires, the system kills your process with a watchdog crash (0x8badf00d).

"SWIFT"
@MainActor
final class SaveCoordinator {
    private var taskID: UIBackgroundTaskIdentifier = .invalid

    func finishSave() {
        taskID = UIApplication.shared.beginBackgroundTask(withName: "Save") {
            self.cancelSaveWork()
            self.endTask()
        }
        guard taskID != .invalid else { return }
        performShortSave { Task { @MainActor in self.endTask() } }
    }

    private func endTask() {
        guard taskID != .invalid else { return }
        UIApplication.shared.endBackgroundTask(taskID)
        taskID = .invalid
    }
}

Isolating SaveCoordinator to @MainActor and hopping back via Task { @MainActor in ... } keeps taskID race-free under Swift 6. Even if work finishes right as the expiration handler fires, endBackgroundTask(_:) runs at most once.

Common mistakes

  • Saving user data only in applicationWillTerminate(_:). Suspended apps are terminated silently under memory pressure without calling it.
  • Skipping endBackgroundTask(_:) inside the expiration handler, which triggers watchdog termination (0x8badf00d) when the background window expires.
  • Assuming beginBackgroundTask gives several minutes. The window is short and finite, so large uploads need a background URLSession.
  • Running heavy disk flushes in sceneWillResignActive(_:) when the user merely pulled down Notification Center or received a call banner.

Follow-up questions

  • "How do ScenePhase.inactive and ScenePhase.background differ in SwiftUI?" ScenePhase.inactive fires while the scene is still visible or transitioning, such as opening Control Center or the app switcher; pause active timers there. ScenePhase.background means the scene left the screen and suspension is coming next; flush durable state and drop caches.
  • "How should you upload a 50 MB receipt video after the user leaves the app?" Do not stretch beginBackgroundTask. Hand the file to a URLSession built with URLSessionConfiguration.background(withIdentifier:) so the OS transfer daemon finishes the upload even while your app is suspended.
  • "Why does UIKit put lifecycle hooks on UISceneDelegate instead of only UIApplicationDelegate?" On iPadOS, one app can show multiple windows at once, each in a different state. One scene can be Active while another is in Background, so UI state transitions belong per scene.

What a strong answer covers

Traces Active, Inactive, Background, Suspended, and Terminated, explains why suspended purge skips applicationWillTerminate(_:), saves in sceneDidEnterBackground or ScenePhase.background, and balances beginBackgroundTask with an expiration handler.

Open in interactive practice deck →

Original OfferVibe question. Managing your app's life cycle · Extending your app's background execution time · SwiftUI ScenePhase.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.