Преглед изворни кода

save when app moves to the background

polscm32 пре 2 година
родитељ
комит
0060038276

+ 6 - 1
FreeAPS/Sources/Application/FreeAPSApp.swift

@@ -65,12 +65,17 @@ import Swinject
     var body: some Scene {
         WindowGroup {
             Main.RootView(resolver: resolver)
-                .environment(\.managedObjectContext, CoreDataStack.shared.persistentContainer.viewContext)
+                .environment(\.managedObjectContext, coreDataStack.persistentContainer.viewContext)
                 .environmentObject(Icons())
                 .onOpenURL(perform: handleURL)
         }
         .onChange(of: scenePhase) { newScenePhase in
             debug(.default, "APPLICATION PHASE: \(newScenePhase)")
+
+            /// If the App goes to the background we should ensure that all the changes are saved from the viewContext to the Persistent Container
+            if newScenePhase == .background {
+                coreDataStack.save()
+            }
         }
     }
 

+ 1 - 1
FreeAPS/Sources/Modules/DataTable/DataTableStateModel.swift

@@ -57,7 +57,7 @@ extension DataTable {
                     }
 
                     taskContext.delete(glucoseToDelete)
-                    
+
                     guard taskContext.hasChanges else { return }
                     try taskContext.save()
                     debugPrint("Data Table State: \(#function) \(DebuggingIdentifiers.succeeded) deleted glucose from core data")

+ 14 - 0
Model/CoreDataStack.swift

@@ -396,6 +396,20 @@ extension CoreDataStack {
 }
 
 // MARK: - Save
+/// This function is used when terminating the App to ensure any unsaved changes on the view context made their way to the persistent container
+extension CoreDataStack {
+    func save() {
+        let context = persistentContainer.viewContext
+
+        guard context.hasChanges else { return }
+
+        do {
+            try context.save()
+        } catch {
+            debugPrint("Error saving context \(DebuggingIdentifiers.failed): \(error)")
+        }
+    }
+}
 
 extension NSManagedObjectContext {
     // takes a context as a parameter to be executed either on the main thread or on a background thread