Source code for the WriteFreely SwiftUI app for iOS, iPadOS, and macOS
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

36 linhas
1.0 KiB

  1. import CoreData
  2. #if os(macOS)
  3. import AppKit
  4. #endif
  5. class PersistenceManager {
  6. let persistentContainer: NSPersistentContainer = {
  7. let container = NSPersistentContainer(name: "LocalStorageModel")
  8. container.loadPersistentStores(completionHandler: { (_, error) in
  9. if let error = error as NSError? {
  10. fatalError("Unresolved error loading persistent store: \(error) - \(error.userInfo)")
  11. }
  12. })
  13. return container
  14. }()
  15. init() {
  16. let center = NotificationCenter.default
  17. #if os(iOS)
  18. let notification = UIApplication.willResignActiveNotification
  19. #elseif os(macOS)
  20. let notification = NSApplication.willResignActiveNotification
  21. #endif
  22. center.addObserver(forName: notification, object: nil, queue: nil) { [weak self] _ in
  23. guard let self = self else { return }
  24. if self.persistentContainer.viewContext.hasChanges {
  25. try? self.persistentContainer.viewContext.save()
  26. }
  27. }
  28. }
  29. }