Since you haven't responded, other than a comment, and you haven't accepted anything as an answer, here's a little more clarification in case you're still misunderstanding how to do this:
Move the fetchRecords method into the DataManager class.
Use a predicate to sort the data rather than sorting it after you've retrieved the records. It's faster.
Change your ViewModel to something like this:
class ViewModel: ObservableObject {
let manager = DataManager()
@Published var records: [Little] = []
init() {
records = manager.fetchRecords()
WidgetCenter.shared.reloadAllTimelines()
}
}
DataManager can be shared between both your iOS target (where ViewModel resides) and your widget target, so change the target membership so it's shared.
In your widget target, your getTimeline method would be something like this:
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
let manager = DataManager()
var items: [Item] = []
for record in manager.fetchRecords() {
let item = Item(trashDate: record.trashDate ?? Date.now, imageSelection: Int(record.imageSelection))
items.append(item)
}
let entry = Timeline(entries: [SimpleEntry(date: Date(), items: items)], policy: .atEnd)
completion(entry)
}
That should show you how to get data from Core Data into your widget.
And, just to answer your other question, no you can't use your ViewModel as it isn't in the widget target, and you cannot call reloadTimelines() from the widget.
If you're still having issues, then I'm sorry, but I've given you all the help I can. You haven't said whether you've attempted anything I've given you.