// // WidgetHelper.swift // Reader // // Created by Shadowfacts on 6/19/22. // import Foundation import WidgetKit import Persistence struct WidgetHelper { private init() {} private static let maxDisplayableItems = 8 static func updateWidgetData(fervorController: FervorController) async { // Accessing CoreData from the widget extension puts us over the memory limit, so we pre-generate all the data it needs and save it to disk let prioritizedItems: [WidgetData.Item] = await fervorController.persistentContainer.performBackgroundTask { ctx in let req = Item.fetchRequest() req.sortDescriptors = [NSSortDescriptor(key: "published", ascending: false)] req.fetchLimit = 32 req.predicate = NSPredicate(format: "read = NO") var items = (try? ctx.fetch(req)) ?? [] var prioritizedItems: [Item] = [] while prioritizedItems.count < maxDisplayableItems { let firstFromUnseenFeedIdx = items.firstIndex { item in prioritizedItems.allSatisfy { existing in existing.feed != item.feed } } if let firstFromUnseenFeedIdx { prioritizedItems.append(items.remove(at: firstFromUnseenFeedIdx)) } else if let item = items.first { prioritizedItems.append(item) items.removeFirst() } else { break } } return prioritizedItems.map { WidgetData.Item(id: $0.id!, feedTitle: $0.feed?.title, title: $0.title, published: $0.published) } } WidgetData(recentItems: prioritizedItems).save(account: fervorController.account!) WidgetCenter.shared.reloadAllTimelines() } }