NotificationsObservable.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import CoreData
  2. import SwiftUI
  3. class NotificationsObservable: NSObject, ObservableObject {
  4. private let tag = "NotificationsObservable"
  5. private var subscriptionID: NSManagedObjectID
  6. private lazy var fetchedResultsController: NSFetchedResultsController<Notification> = {
  7. let fetchRequest: NSFetchRequest<Notification> = Notification.fetchRequest()
  8. // Filter by the desired subscription
  9. fetchRequest.predicate = NSPredicate(format: "subscription == %@", subscriptionID)
  10. // Sort descriptors if you need them
  11. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "time", ascending: false)] // Assuming you have a 'date' attribute on the NotificationEntity
  12. let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: Store.shared.context, sectionNameKeyPath: nil, cacheName: nil)
  13. controller.delegate = self
  14. return controller
  15. }()
  16. @Published var notifications: [Notification] = []
  17. init(subscriptionID: NSManagedObjectID) {
  18. self.subscriptionID = subscriptionID
  19. super.init()
  20. do {
  21. Log.d(tag, "Fetching notifications")
  22. try self.fetchedResultsController.performFetch()
  23. self.notifications = self.fetchedResultsController.fetchedObjects ?? []
  24. } catch {
  25. Log.w(tag, "Failed to fetch notifications \(error)")
  26. }
  27. }
  28. }
  29. extension NotificationsObservable: NSFetchedResultsControllerDelegate {
  30. func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
  31. DispatchQueue.main.async {
  32. self.notifications = self.fetchedResultsController.fetchedObjects ?? []
  33. }
  34. }
  35. }