swift - 当我的核心数据存储从后台扩展更新时,如何刷新我的 SwiftUI View ?

标签 swift core-data swiftui intents-extension

我有一个带有意图扩展目标的 SwiftUI 应用程序。我还有一个位于共享应用程序组的核心数据存储。

意图扩展可以使用 newBackgroundContext() 成功地将数据写入存储。在快捷方式应用程序中。我的 SwiftUI 应用可以从 viewContext 中的应用组读取数据但只有当我强制退出应用程序并重新打开它时。

我想我需要一种方法让我的应用知道它已在不同的上下文中更新,但我不确定如何做到这一点?

我试过设置context.automaticallyMergesChangesFromParent = true在应用程序委托(delegate)中添加 context.refreshAllObjects()onAppear在 SwiftUI View 中,但这似乎没有任何区别。

mergeChanges(fromContextDidSave:)似乎很有希望,但我不确定如何获得通知。

我是 Core Data 的新手并且非常困惑,所以任何正确方向的指针都会很棒,谢谢!

这是我当前代码的净化版本:

应用代表

 lazy var persistentContainer: NSCustomPersistentContainer = {
        let container = NSCustomPersistentContainer(name: "exampleContainerName")
        container.loadPersistentStores { description, error in
            if let error = error {
                print("error loading persistent core data store")
            }
        }
        return container
    }()

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                print("error saving core data context")
            }
        }
    }

class NSCustomPersistentContainer: NSPersistentContainer {
    override open class func defaultDirectoryURL() -> URL {
        var storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "exampleAppGroupName")
        storeURL = storeURL?.appendingPathComponent("exampleContainerName")
        return storeURL!
    }
}

场景代表
guard let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext else {
            fatalError("Unable to read managed object context.")
}

if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: ExampleView.environment(\.managedObjectContext, context))
            self.window = window
            window.makeKeyAndVisible()
}

Swift UI View
import SwiftUI
import CoreData

struct ExampleView: View {

    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(
        entity: ExampleEntityName.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \ExampleEntityName.date, ascending: false),
        ]
    ) var items: FetchedResults<ExampleEntityName>

    var body: some View {
        VStack {
            List(items, id: \.self) { item in
                Text("\(item.name)")
            }
        }
    }
}

意向扩展
class NSCustomPersistentContainer: NSPersistentContainer {
    override open class func defaultDirectoryURL() -> URL {
        var storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "exampleContainerName")
        storeURL = storeURL?.appendingPathComponent("exampleAppGroupName")
        return storeURL!
     }
}

let persistentContainer: NSCustomPersistentContainer = {
    let container = NSCustomPersistentContainer(name: "exampleContainerName")
    container.loadPersistentStores { description, error in
        if let error = error {
            print("error loading persistent core data store: \(error)")
        }
    }
    return container
}()

let context = persistentContainer.newBackgroundContext()

let entity = NSEntityDescription.entity(forEntityName: "ExampleEntityName", in: context)
let newEntry = NSManagedObject(entity: entity!, insertInto: context)
newEntry.setValue(Date(), forKey: "date")
newEntry.setValue("Hello World", forKey: "name")

do {
    try context.save()
} catch {
    print("Failed saving")
}

最佳答案

不知道您是否找到了答案,但我在共享应用程序组中使用 UserDefaults 和意图扩展时遇到了类似的问题。最终对我有用的事情是在 SceneDelegate 的以下方法中添加调用以加载项目:

func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
        SiriResponseManager.shared.grabUD()
    }

在我的示例中,我使用了一个单例,其中包含从 UserDefaults 加载项目的方法。这个单例类是一个 ObservableObject。在我加载的第一个 View (在我的情况下为 ContentView)中,我将 ObservedObject 变量分配给我的单例类并检索我的单例中的 @State 变量以在我的 View 中填充字符串。

希望这会有所帮助。

关于swift - 当我的核心数据存储从后台扩展更新时,如何刷新我的 SwiftUI View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579410/

相关文章:

ios - 如何在预览 View 层上设置相机大小

ios - 如何以某种通用方式删除有序的对多 CoreData 关系中的对象?

swift - SwiftUI View 中修饰符的顺序会影响 View 外观

iphone - 将本地 SQLite 数据库复制到 iPhone?

ios - Swift - 将核心数据检索到自定义单元格

ios - SwiftUI 在一种情况下查看层次结构警告,而不是另一种情况

ios - 在 swiftui 中使用类

swift - 如何使用 AlamofireImage ProgressHandler

swift - Firebase InstanceID.instanceID().token() 方法已弃用

ios - 如何让带有嵌入式 UITableView 的 ContainerView 随着 tableView 单元格数量的变化而更新高度约束