Post

Replies

Boosts

Views

Activity

Reply to WidgetKit and CoreData/CloudKit
Short Answer: You can't achieve Core Data / iCloud sync with NSPersistentCloudKitContainer in Widgets I ran many tests with and without WidgetKit and I discovered that no matter what I tried, I could never get NSPersistentCloudKitContainer to sync while an app is in the background. There is no amount of time that you can wait either, the sync will simply not happen. I tried querying Core Data during BackgroundTasks and the data is simply never there. I can see that a sync operation gets queued with a priority of 2 but only when an app becomes active does the sync even run. Widgets always run in the background. Since NSPersistentCloudKitContainer only runs while an app is in the foreground and since widgets only run in the background, the sync will never happen unless you launch the app. This isn't ideal because say you have the app installed on another device like a watch, your widget on your phone will never receive the updates that you do on the watch. At least, not with NSPersistentCloudKitContainer. After contacting Apple, they confirmed that this is what is happening. To make matters worst, the sync operation is not publicly exposed therefore you can't manually trigger it. Their solution is to manually sync your records using CloudKit and store that data into Core Data manually, which, imo, defeats the purpose of NSPersistentCloudKitContainer. Now truth be told, you don't really need the entire database data in your widget, so you can just take a snapshot of the data that you need, store that in CloudKit and retrieve it in your widget manually as needed. I strongly recommend that anyone who needs NSPersistentCloudKitContainer to run in the background send Apple some feedback. If enough of us do, they might introduce this feature in the future.
Nov ’20