I use NSPersistentCloudKitContainer
to fetch/sync data across multiple devices with the same iCloud account.
/// ...
container = NSPersistentCloudKitContainer(name: containerName)
let description = container.persistentStoreDescriptions.first
description?.setOption(
true as NSNumber,
forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
description?.setOption(
true as NSNumber,
forKey: NSPersistentHistoryTrackingKey)
let viewContext = container.viewContext
viewContext.automaticallyMergesChangesFromParent = true
viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
NotificationCenter.default.addObserver(
forName: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator,
queue: .main
) { _ in
Task { @MainActor [weak self] in
// fetch new data and update widgets with it
// ... viewContext.fetch ...
// WidgetCenter.shared.reloadAllTimelines()
}
}
}
/// ...
Everything works fine when my app in the foreground. How can I achieve the same when my app is closed/ in the background? I know that CloudKit can send silent push notification which can wake up my app but I've never seen the implementation of it using CoreData NSPersistentCloudKitContainer