Saving Data When Your Swift App Quits

A common scenario for iOS and Mac apps is to save data when someone quits the app. You have written a function to save the data. Where do you make the call when the app quits? This article answers that question, both for the SwiftUI app life cycle and the classic AppDelegate life cycle.

Using the SwiftUI App Life Cycle

In Xcode 12 Apple introduced a native SwiftUI app life cycle. The new life cycle has a scenePhase environment value that stores the app’s current phase, such as active, inactive, or background.

Add a property to the app struct for the scene phase. Add the .onChange modifier to the app’s window group or document group. Check if the phase is .background. If it is, make a call to save the data. The following code shows how to check when the app goes in the background:

@main
struct MySwiftUIApp: App {
  @Environment(\.scenePhase) private var scenePhase
    
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
    .onChange(of: scenePhase) { phase in
      if phase == .background {
        // Save here
      } 
    }
	}
} 

Using the AppDelegate Life Cycle

If your Xcode project has a file named AppDelegate.swift, it is using the AppDelegate life cycle. Open the AppDelegate.swift function, and you should see multiple empty functions for handling app events.

An iOS app that wants to save when someone quits the app should make a call to save the data in the function applicationDidEnterBackground. This function is called when the person quits your app.

func applicationDidEnterBackground(_ application: UIApplication) {
  // Save here
}

A Mac app should make the save call in applicationWillTerminate.

func applicationWillTerminate(_ aNotification: Notification) {
  // Save here
}

Get the Swift Dev Journal Newsletter

Subscribe and get exclusive articles, a free guide on moving from tutorials to making your first app, notices of sales on books, and anything I decide to add in the future.

    We won't send you spam. Unsubscribe at any time.