Source code for the WriteFreely SwiftUI app for iOS, iPadOS, and macOS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

66 lines
2.2 KiB

  1. import CoreData
  2. #if os(iOS)
  3. import UIKit
  4. #elseif os(macOS)
  5. import AppKit
  6. #endif
  7. final class LocalStorageManager {
  8. public static var standard = LocalStorageManager()
  9. public let container: NSPersistentContainer
  10. init() {
  11. // Set up the persistent container.
  12. container = NSPersistentContainer(name: "LocalStorageModel")
  13. container.loadPersistentStores { description, error in
  14. if let error = error {
  15. fatalError("Core Data store failed to load with error: \(error)")
  16. }
  17. }
  18. container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  19. let center = NotificationCenter.default
  20. #if os(iOS)
  21. let notification = UIApplication.willResignActiveNotification
  22. #elseif os(macOS)
  23. let notification = NSApplication.willResignActiveNotification
  24. #endif
  25. // We don't need to worry about removing this observer because we're targeting iOS 9+ / macOS 10.11+; the
  26. // system will clean this up the next time it would be posted to.
  27. // See: https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver
  28. // And: https://developer.apple.com/documentation/foundation/notificationcenter/1407263-removeobserver
  29. // swiftlint:disable:next discarded_notification_center_observer
  30. center.addObserver(forName: notification, object: nil, queue: nil, using: self.saveContextOnResignActive)
  31. }
  32. func saveContext() {
  33. if container.viewContext.hasChanges {
  34. do {
  35. try container.viewContext.save()
  36. } catch {
  37. print("Error saving context: \(error)")
  38. }
  39. }
  40. }
  41. func purgeUserCollections() {
  42. let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "WFACollection")
  43. let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
  44. do {
  45. try container.viewContext.executeAndMergeChanges(using: deleteRequest)
  46. } catch {
  47. print("Error: Failed to purge cached collections.")
  48. }
  49. }
  50. }
  51. private extension LocalStorageManager {
  52. func saveContextOnResignActive(_ notification: Notification) {
  53. saveContext()
  54. }
  55. }