Dear Ziqiao Chen,
thank you for your reply and the hints pointing me in the right direction. I managed to solve my problem no. 1 and now the sync works both between the app and the widget, but also between different devices.
I had already observed the .NSPersistentStoreRemoteChange notification in my sample project, but it turns out that wasn't even necessary when automaticallyMergesChangesFromParent is set to true on the viewContext.
The Problem with Syncing from a Widget
Now the problem is the following:
Regarding using Core Data + CloudKit (NSPersistentCloudKitContainer) in an extension, I'd like to suggest against doing that
⬆️ Your reply and the linked Technical Note both imply that syncing data with iCloud this way from both the app and its widget is not reliable as two NSPersistentCloudKitContainers pointing to the same persistent store can get in conflict (running on different threads) and throw the following error:
CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process.
In other words: I cannot do that in a production app.
From Avoid synchronizing a store with multiple persistent containers:
When working with an extension, you don’t control its lifecycle. It is perfectly possible that your extension is launched when your app is running, or vice versa, and both of them try to load the shared store.
To avoid the conflict, consider having the app in charge of the synchronization. An extension that has the capability to present UI can remind users to launch the app to synchronize with CloudKit, if that is an appropriate user experience.
So now I know what doesn't work. My question is: What does?
What's the recommended, safe approach to sync data from an interactive widget with iCloud?
Showing a hint to users inside the widget that they should open the main app in order to sync is hardly a practical solution and destroys not only the user experience, but the very purpose of interactive widgets. If I need to open the app each time I've pressed a button on the widget, it's not very interactive after all.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: