How to Automatically Reflect Coredata+Icloud Changes in Swiftui View

Toggle iCloud sync during runtime

Declare your variable as a NSPersistentContainer instead of NSPersistentCloudKitContainer. On launch, if the user has cloud sync, load the cloud kit persistent container, otherwise load the non-cloud kit one.

When the switch is toggled, reload the container, following the same rules. To reload the container, I would add the property to a manager object, in which I would add some methods that reload the the container depending on the user's settings.

CoreData and CloudKit Sync works, but NSPersistentStoreRemoteChange notification never fires

I have the same problem, and solved by configuring custom persistent store descriptions before calling loadPersistentStores(completionHandler:)

container = NSPersistentCloudKitContainer(name: "RubikClub")
// turn on persistent history tracking
let description = container.persistentStoreDescriptions.first
description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description?.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
NotificationCenter.default.addObserver(self, selector: #selector(type(of: self).storeRemoteChange(_:)), name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)

container.loadPersistentStores { (_, error) in
if let error = error {
fatalError("init core data error: \(error.localizedDescription)")
}
}
container.viewContext.automaticallyMergesChangesFromParent = true

How to keep data from iCloud(CloudKit) loaded after switching view controllers

There are a couple ways to approach this problem.

You will want to pass your data and the context from one view controller to the next. Make sure you remove the code in your second view controller the refetches the data.

The way I've chosen to do it is to pass the data from one to the next in the prepareForSegue function like so.

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "mysegue"
{ let destinationViewController = (segue.destinationViewController as! UITabBarController) as! SecondViewController
destinationViewController.myData = myData
destinationViewController.context = stack.context
}
}


Related Topics



Leave a reply



Submit