我的 SwiftUI 应用程序收到无声远程通知。它不是由 UNUserNotificationCenter 拾取,而是由旧的 AppDelegate didReceiveNotification 函数拾取。通知 ContentView() 发生更改的解决方案是什么? AppDelegate 中的 ObservableObject?
最佳答案
您可以在 AppDelegate 中声明一个符合 ObservableObject
的 store,并将其设置为 ContentView 的环境对象。
// AppDelegate.swift
// in the class
let store = Store()
// in the applicationDidFinishLaunching(_:) method
window.contentView = NSHostingView(rootView: contentView.environmentObject(store))
// ContentView.swift
// in the struct
@EnvironmentObject var store: Store
环境对象是一个引用,因此您可以将值传递给它。与使用 ObservableObject 相同。完成更新后,只需调用 objectWillChange.send()
或将属性标记为 @Published。 ContentView会在收到通知后更新。
关于AppDelegate 和 ContentView() 之间的 SwiftUI 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61832113/