0

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()
Yu23333
  • 46
  • 5
  • I'm having a similar issue: https://stackoverflow.com/questions/67482411/ios-14-widget-works-locally-but-fails-via-testflight. I would love to know what you're doing with the `tasks` property in `SimpleEntry`. I'm having a hard time integrating CloudKit into my Widget, and I suspect it has to do with the CloudKit call taking too long. I'd love to know how you handle it for core data. Thanks! – West1 May 20 '21 at 14:54
  • 1
    @West1 Hello, I have solved my problem. Please check the "Update" section. And I have checked your post, did you deploy the cloudkit container to the production? You can find it on the CloudKit Dashboard. – Yu23333 May 21 '21 at 15:15
  • It appears that deploying the CloudKit container to production is the answer to my problem. I've been struggling with this issue for two weeks, and you just casually solved it. If you post an answer to my question, I will accept it. Thank you so much! You've made my day! :) – West1 May 21 '21 at 17:32
  • @West1 Glad to hear that! – Yu23333 May 22 '21 at 20:24

1 Answers1

0

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()
Yu23333
  • 46
  • 5