Skip to content

Instantly share code, notes, and snippets.

@voncannon
Last active May 10, 2024 15:10
Show Gist options
  • Save voncannon/621c35a55db722a8c2d81835934f5002 to your computer and use it in GitHub Desktop.
Save voncannon/621c35a55db722a8c2d81835934f5002 to your computer and use it in GitHub Desktop.
Core Data Save Extensions - Save if app is backgrounded
//
// 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