Run Code When iOS App Terminates in Background
In this article
Yes—you can run code when an iOS app is terminated while in the background by handling the appropriate delegate callbacks and, when possible, using a background task to finish critical work before the system kills the process.
What You'll Need
- Xcode installed on a macOS computer
- An iOS project targeting iOS 13 or later (the APIs used are stable across recent versions)
- Basic familiarity with Swift (or Objective‑C) and the UIApplicationDelegate lifecycle
- A device or simulator for testing; real‑device testing is recommended for termination scenarios
Step‑By‑Step
- Open your project in Xcode and locate the class that conforms to
UIApplicationDelegate(usuallyAppDelegate.swift). - Add a property to keep a reference to any background task you start:
This identifier lets you tell the system when you have finished the work you need to complete.var backgroundTask: UIBackgroundTaskIdentifier = .invalid - Implement
applicationWillTerminate(_:). This method is called when the user explicitly quits the app (for example, by swiping it away in the app switcher) and also when the system is about to terminate the app after it has been in the background for a long time.func applicationWillTerminate(_ application: UIApplication) { // Start a short‑lived background task so the system gives you time to finish. startBackgroundTask() // Place the code you need to run here – e.g., saving user data, closing network sockets, flushing logs. performCriticalCleanup() // End the background task when you are done. endBackgroundTask() } - Define the helper methods used above:
The system typically gives you about 30 seconds of execution time after you callfunc startBackgroundTask() { backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "AppTerminationTask") { // This closure is called if the time expires before you call endBackgroundTask. self.endBackgroundTask() } if backgroundTask == .invalid { print("Failed to start background task") } } func endBackgroundTask() { if backgroundTask != .invalid { UIApplication.shared.endBackgroundTask(backgroundTask) backgroundTask = .invalid } } func performCriticalCleanup() { // Example: write unsaved changes to disk DataManager.shared.savePendingChanges() // Example: send a final analytics ping Analytics.shared.flush() // Add any other work that must not be lost. }beginBackgroundTask. Use this window wisely; do not perform long‑running loops or heavy processing. - If your app is likely to be terminated without
applicationWillTerminate(for example, when the user force‑quits the app from Settings or the OS reclaims memory), you should also listen for theUIApplication.willTerminateNotificationnotification in any object that needs to react.NotificationCenter.default.addObserver(self, selector: #selector(handleWillTerminate), name: UIApplication.willTerminateNotification, object: nil) @objc func handleWillTerminate() { startBackgroundTask() performCriticalCleanup() endBackgroundTask() } - Consider using
applicationDidEnterBackground(_:)as a fallback. When the app moves to the background you can start a background task to give yourself extra time to finish work before iOS may later callapplicationWillTerminate.func applicationDidEnterBackground(_ application: UIApplication) { startBackgroundTask() // Prepare data that might be needed later. cacheImportantState() // Do not end the task here; let it finish when the app actually terminates. } - Test the behavior:
- Run the app on a device.
- Press the Home button to send it to the background.
- Open the app switcher and swipe the app away. Observe the console output for the "performCriticalCleanup" log.
- To simulate a forced termination by the system, enable "Debug > Simulate Memory Warning" or let the device run low on memory while the app is in the background. The system may kill the app without calling
applicationWillTerminate; verify that any state saved earlier inapplicationDidEnterBackgroundis persisted.
- Optional: If you need to guarantee execution even when the app is killed abruptly (for example, after a crash), consider using a silent push notification or a background fetch to wake the app later and complete the pending work. These mechanisms are separate from termination handling and require proper entitlement configuration.
Common Mistakes
- Assuming
applicationWillTerminateis always called. iOS may skip this callback when the app is killed for memory pressure or when the user force‑quits from Settings. - Starting a background task but never ending it. Failing to call
endBackgroundTaskwill cause the system to terminate your app after the allotted time, potentially leading to data loss. - Doing heavy processing inside the termination callback. The system only grants a short window; lengthy tasks will be cut off.
- Relying on UI updates inside
applicationWillTerminate. The UI is not visible in the background, and attempts to modify it can cause warnings. - Neglecting to test on a real device. Simulators do not always emulate termination behavior accurately.
Tips
- Keep the cleanup code modular. A single method like
performCriticalCleanupmakes it easy to call from multiple lifecycle points. - Persist data to disk (or Core Data) as soon as you have a chance, rather than waiting for termination. This reduces reliance on the termination callback.
- Log the start and end of your background task. If the task is aborted, the log will help you understand where the cutoff occurred.
- Use
DispatchQueue.global(qos: .background)for any non‑UI work inside the task to avoid blocking the main thread. - Set the "Background Modes" capability to "Background fetch" if you plan to use fetch or silent push as a backup strategy.
Troubleshooting
If your code does not run when the app is terminated, follow these steps:
- Check that the delegate method is actually being called. Add a simple
print("willTerminate called")statement at the top ofapplicationWillTerminate. Run the app, background it, and swipe it away. If you see the log, the method is firing. - Verify the background task identifier. If
beginBackgroundTaskreturns.invalid, the system denied the request. Ensure your app has the "Background Modes" capability enabled (even though the task itself does not require a specific mode, some configurations can interfere). - Make sure you end the task. If the console shows "Time remaining: 0.0 seconds" before your cleanup finishes, you likely exceeded the time limit. Reduce the work or split it into smaller chunks.
- Use
DispatchQueue.global().asyncAfter(deadline: .now() + 25) { self.endBackgroundTask() }as a safety net to avoid the system killing you.
- Use
- Test forced termination. Go to Settings > General > iPhone Storage, find your app, and tap "Delete App" while it is in the background. This action kills the process without calling
applicationWillTerminate. Confirm that any state saved earlier (e.g., inapplicationDidEnterBackground) is still present on next launch. - Check for accidental early returns. If you have guard statements that exit the cleanup method before critical code runs, the task may end without doing anything.
- Review console warnings. iOS prints messages such as "Application finished background task without calling endBackgroundTask". These indicate a missing
endBackgroundTaskcall. - Update Xcode and iOS. Occasionally, bugs in older SDKs affect termination callbacks. Using the latest stable release reduces this risk.
Frequently Asked Questions
Will applicationWillTerminate run if the user force‑quits the app from the app switcher?
Yes. Swiping the app away in the app switcher triggers applicationWillTerminate, giving you a short window to finish work.
What if iOS kills my app for memory pressure without calling applicationWillTerminate?
In that case the termination callback is skipped. You should save any essential state in applicationDidEnterBackground or use persistent storage as soon as possible.
Can I run unlimited code after termination?
No. iOS grants roughly 30 seconds after you start a background task. Exceeding this limit results in the system terminating the process.
Do I need special entitlements to use beginBackgroundTask?
No special entitlement is required for a short‑lived termination task, but you must enable the "Background Modes" capability if you also use background fetch, remote notifications, or other persistent background features.
Is it safe to make network requests during termination?
Yes, but keep them brief. Initiate the request, wait for the response, and end the background task as soon as the request finishes or the time limit approaches.
Will silent push notifications help if the app is already terminated?
Silent pushes can wake a terminated app, allowing you to perform work later. They are a separate mechanism and require proper APNs configuration and the "Remote notifications" background mode.