How to automatically reflect CoreData+iCloud Changes in SwiftUI view?

荒凉一梦 提交于 2020-12-01 11:19:26

问题


🤓 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

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