CloudKit notification is fireing many times on one import

82 views Asked by At

I've set up a Notification listener which should fire when the CloudKit (NSPersistentCloudKitContainer) import is finished (so once), but the notification gets fired twice, sometimes thrice on one View.

Maybe it's the code that is wrong, or maybe CloudKit is doing several imports on one request and that is expected behavior (doubt it).

Here is my (faulty) notification listener code:

struct MainView: View {
    var body: some View {
        Text("Example")

        .onReceive(NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification)
            .receive(on: DispatchQueue.main)) { notification in

            if let cloudEvent = notification.userInfo?[NSPersistentCloudKitContainer.eventNotificationUserInfoKey]
                as? NSPersistentCloudKitContainer.Event {

                //NSPersistentCloudKitContainer sends a notification when an event starts, and another when it ends.
                //If it has an endDate, it means the event has finished.
                if cloudEvent.succeeded && cloudEvent.endDate != nil && cloudEvent.type == .import {
                    print("Import is finished!")
                }
            }
        }
    }
}

When I open my app and sync local Core Data with CloudKit (which is done automatically via NSPersistentCloudKitContainer) I get "Import is finished!" printed 2-3 times. Why?

0

There are 0 answers