Thanks.
Code Block swift @main struct SampleApp: App { @Environment(\.scenePhase) private var scenePhase var body: some Scene { WindowGroup { MovieList() .environment(\.managedObjectContext, persistentContainer.viewContext) } .onChange(of: scenePhase) { phase in switch phase { case .active: print("active") case .inactive: print("inactive") case .background: print("background") saveContext() } } } var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "SampleApp") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() func saveContext() { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }