AppDelegate 和 ContentView() 之间的 SwiftUI 通信



我在 SwiftUI 应用程序上收到一个静默的远程通知。它不是由UNUserNotificationCenter拾取的,而是由旧的AppDelegate didReceiveNotification func拾取的。通知 ContentView(( 发生了更改的解决方案是什么?AppDelegate 中的 ObservableObject?

您可以在应用程序委托中声明符合ObservableObject的存储,并将其设置为内容视图的环境对象。

// 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。并且内容视图将在通知后更新。

最新更新