问题
🤓 So...I have an app with StoreData and iCloud enabled. My data is syncing between the devices but I don't ge the behaviour I want when it comes to reflecting the changes in the UI.
The behaviour I want: When a user has my app open on two devices (A & B) and makes a change one one (A) of them I want the change to automatically reflect in the second (B) device UI within some reasonable time.
The behaviour I currently have: When the user makes changes on one device (A) nothing ever happens on the other (B)...until I minimise and maximise the app on the second device (B) (Not restarting...just minimising).
🤔 My thought are that the app won't receive the changes (iCloud won't sync) until some action is triggered when minimising and reopening the app.
🥺 But I don't know. According to Syncing a Core Data Store with CloudKit syncing and notifying other devices should happened automatically. And I think my View should be hooked up correctly as it will change instantly when making local changes to data in the CoreData database.
My SwiftUI view pretty much looks like this:
import SwiftUI
import CloudKit
import Foundation
struct MyView: View {
@FetchRequest(fetchRequest: Entity.fetchRequest() as! NSFetchRequest<Entity>) var entities: FetchedResults<Entity>
var body: some View {
List {
ForEach(entities, id: \.id) { e in
Text("\(e.title)")
}
}
}
}
public class Entity: NSManagedObject {
@NSManaged public var id: UUID?
@NSManaged public var title: String
}
Any Help is much appreciated! (Let me know if I need to provide additional information.)
回答1:
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "ComCloudSync")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
Try adding the following code (change "ComCloudSync" to your appName):
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "ComCloudSync")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
return container
}()
来源:https://stackoverflow.com/questions/60532782/how-to-automatically-reflect-coredataicloud-changes-in-swiftui-view