Why does iOS lose unsaved form data without calling willTerminate?
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.
- Trace the iOS lifecycle states after switching to Mail, and explain why
applicationWillTerminate(_:)never ran. - How do you persist state reliably and use
beginBackgroundTasksafely?
Show hints (3)
- "WHAT HAPPENS WHEN SUSPENDED"
After entering the background, iOS freezes your app in the
Suspendedstate. Does iOS wake a frozen process before reclaiming its memory? - "PERSIST BEFORE FREEZING"
Save critical user edits incrementally, or at the latest inside
sceneDidEnterBackground(_:)or SwiftUIScenePhase.background. - "BALANCE EVERY BACKGROUND TASK"
beginBackgroundTaskgrants only a short finite window. Every non-.invalidID must callendBackgroundTask(_:)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:
| state | visible on screen | CPU runs | what your app should do |
|---|---|---|---|
Active | yes | yes | run UI, timers, and user interactions |
Inactive | partial or transitioning | yes | pause gameplay or live timers |
Background | no | briefly | save critical data and release heavy caches |
Suspended | no | no | frozen in RAM; iOS may purge silently |
Terminated | no | no | process 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).
@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
beginBackgroundTaskgives several minutes. The window is short and finite, so large uploads need a backgroundURLSession. - 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.inactivefires while the scene is still visible or transitioning, such as opening Control Center or the app switcher; pause active timers there.ScenePhase.backgroundmeans 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 aURLSessionbuilt withURLSessionConfiguration.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
Activewhile another is inBackground, 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 →