Source code for the WriteFreely SwiftUI app for iOS, iPadOS, and macOS
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

50 líneas
1.7 KiB

  1. import CoreData
  2. #if os(iOS)
  3. import UIKit
  4. #elseif os(macOS)
  5. import AppKit
  6. #endif
  7. class PersistenceManager {
  8. let persistentContainer: NSPersistentContainer = {
  9. let container = NSPersistentContainer(name: "LocalStorageModel")
  10. container.loadPersistentStores(completionHandler: { (_, error) in
  11. if let error = error {
  12. fatalError("Unresolved error loading persistent store: \(error)")
  13. }
  14. })
  15. return container
  16. }()
  17. init() {
  18. let center = NotificationCenter.default
  19. #if os(iOS)
  20. let notification = UIApplication.willResignActiveNotification
  21. #elseif os(macOS)
  22. let notification = NSApplication.willResignActiveNotification
  23. #endif
  24. // We don't need to worry about removing this observer because we're targeting iOS 9+ / macOS 10.11+; the
  25. // system will clean this up the next time it would be posted to.
  26. // See: https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver
  27. // And: https://developer.apple.com/documentation/foundation/notificationcenter/1407263-removeobserver
  28. // swiftlint:disable:next discarded_notification_center_observer
  29. center.addObserver(forName: notification, object: nil, queue: nil) { [weak self] _ in
  30. guard let self = self else { return }
  31. self.saveContext()
  32. }
  33. }
  34. func saveContext() {
  35. if persistentContainer.viewContext.hasChanges {
  36. do {
  37. try persistentContainer.viewContext.save()
  38. } catch {
  39. print("Error saving context: \(error)")
  40. }
  41. }
  42. }
  43. }