I have an app which uses SwiftData and CloudKit all works fine and well. Now I wanted to implement a feature which lets the user know that there are data incoming from the cloud and they have to wait a little bit for the data to show up. Furthermore my app needs to do some data sanitation when it starts up. This sanitation should only be done after the CloudKit updates are processed.
So is there a way that my app can know when CloudKit is doing updates and when it is finished? I was looking for some kind of notification but couldn’t find any info on that.
I don’t need to know which data are updated or process the data. I just want to get notified when a sync starts and when it has ended. Actually it would suffice to know when a sync is finished.
SwiftData + CloudKit integration is based NSPersistentCloudKitContainer
as of today, and so you can observe the synchronization events using eventChangedNotification with the following steps:
- Observe the
eventChangedNotification
notification. - In your notification handler, use
eventNotificationUserInfoKey
to retrieve the the event fromnotification.userInfo
. - Look into the event type, startDate, and endDate to understand the state of the event.
For a runnable sample, please see Sharing Core Data objects between iCloud users. It is a Core Data sample, but the way to observe eventChangedNotification
can be applied to SwiftData.
Note that eventChangedNotification
tells you the state of an individual export
or import
event, and not that the whole Core Data store is synchronized with the CloudKit server (or not), because there may have new changes happening on the CloudKit server while the event is being handled.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.