'CoreData not updated until application inactivates
I'm building a Macos CoreData+CloudKit app.
I first create my container by doing this:
let container = NSPersistentCloudKitContainer(name: "TestApp")
let description = container.persistentStoreDescriptions.first
description?.setOption(true as NSNumber,
forKey: NSPersistentHistoryTrackingKey)
let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey"
description?.setOption(true as NSNumber,
forKey: remoteChangeKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
fatalError("Unresolved error \(error)")
}
})
I'm registering to receive remote changes by doing this:
NotificationCenter.default.addObserver(
self,
selector: #selector(fetchChanges),
name: NSNotification.Name(
rawValue: "NSPersistentStoreRemoteChangeNotification"),
object: persistentContainer.persistentStoreCoordinator
)
And in fetchChanges
, I just reload my UI by
- Fetching the data
- Reloading my tableView
However, I found out that fetchChanges
is never called until the application inactivates. I see this in the log as:
CoreData: debug: CoreData+CloudKit: -[PFCloudKitThrottledNotificationObserver noteRecievedNotification:](40): <PFCloudKitThrottledNotificationObserver: 0x600003fb3fc0>: Got: NSApplicationWillBecomeActiveNotification - 0
What I'm assuming is happening is when CoreData detects my window inactivates via the NSApplicationWillBecomeActiveNotification
event, it spawns a background task to fetch the remote iCloud
data into the local store.
At that point, the NSPersistantStoreRemoteChangeNotification
is received.
My question is how do you force the local store to sync with iCloud
?
Any help is greatly appreciated.
Solution 1:[1]
Some possible clues:
- You need to activate "Background fetch" in the "Background Modes" of the target's Signing & Capabilities
- This happened to me because I needed to sign in to iCloud again (I had a prompt in the Settings, but if you don't it's worth trying to sign out and sign back in)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Arnaud |