I use the following code to update my widget's timeline, but the "result" which I fetched from the core data is not up-to-date.
My logic is when detecting the host app goes to background I call "WidgetCenter.shared.reloadAllTimelines()" and fetch the core data in the "getTimeline" function. After printing out the result, it is old data. Also I fetch the data with the same predicate under the .background, the data is up-to-date.
Also I show the date in the widget view body, when I close the host app, the date is refreshing. Means that the upper refreshing logic works fine. But just always get the old data.
Could someone help me out?
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
let now = Date()
let newRequest = coreDataManager.fetchRequestForTimeline(date: now)
let result = try? viewContext.fetch(newRequest)
print(result!)
print("new####")
entries.append(SimpleEntry(date: now, tasks: result))
let timeline = Timeline(entries: entries, policy: .never)
completion(timeline)
}
This is the code in the host app
case .background:
WidgetCenter.shared.reloadAllTimelines()
// fetch here
print("App is in background")
Update:
I added the following code to refresh the core data before I fetch. Everything work as expect.
// refresh the core data
try? viewContext.setQueryGenerationFrom(.current)
viewContext.refreshAllObjects()