Core Data + CloudKit not refreshing on other device automatically?

陌路散爱 提交于 2021-01-29 13:38:56

问题


I have my SwiftUI app working with Core Data + CloudKit. I am able to save new entries to the database from my Mac or iPhone. The app uses the exact same project/codebase for all devices.

The only problem is that I need to close out of the app and re-open it to see any new entries made from the other device. I can immediately see the new entries made from the same device, but they do not appear on the other devices until I close and re-open the app on it.

Am I missing something here? Do I need to add something like ObservableObject or Identifiable to my Entity class? How do I correct this issue?

Edit:

Here is how I obtain the records:

@FetchRequest(
    entity: Doc.entity(),
    sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)]
) var docs: FetchedResults<Doc>

回答1:


Figured it out!

I had to add:

context.automaticallyMergesChangesFromParent = true

To the scene() function in SceneDelegate:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
context.automaticallyMergesChangesFromParent = true

Now its working flawlessly.

Credit: https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/



来源:https://stackoverflow.com/questions/58860967/core-data-cloudkit-not-refreshing-on-other-device-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!