Last active
May 10, 2024 15:10
-
-
Save voncannon/621c35a55db722a8c2d81835934f5002 to your computer and use it in GitHub Desktop.
Core Data Save Extensions - Save if app is backgrounded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSManagedObjectContext+Extensions.swift | |
// Topo Lock Maps | |
// | |
// Created by VonCannon Technology, Inc. on 12/8/23. | |
// | |
import Foundation | |
import UIKit | |
import CoreData | |
extension NSManagedObjectContext { | |
func saveIfChanged() throws { | |
guard hasChanges else { return } | |
try save() | |
} | |
/// This saves the managed object context only if the context has changes and the app is backgrounded. | |
/// Useful during background location updates since we do not know when the app will be killed (battery dies, user turns off device, etc.) so we can save updates along the way. | |
func saveIfChangedAndAppIsBackgrounded() throws { | |
let isAppBackgrounded = UIApplication.shared.applicationState != .active | |
guard isAppBackgrounded else { | |
return | |
} | |
try saveIfChanged() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment