SwiftUI:从 AppDelegate 访问 @EnvironmentObject

SwiftUI: Access @EnvironmentObject from AppDelegate

我想使用 applicationWillTerminate 函数在应用程序关闭前保存一些用户默认值。我要保存的数据存储在 EnvironmentObject 中。

如何从 AppDelegate class 访问它?

@EnvironmentObject 不需要在您的 SwiftUI 对象中直接实例化;相反,它可以分配到其他地方(例如,您的 UISceneDelegate),然后使用 .environment(…) 函数传递。

您也可以在您的 AppDelegate 上分配它,然后将该对象传递给您在 UISceneDelegate.scene(_:willConectTo:options:) 方法中的视图。

Paul Hudson 在 https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

上对所有这些都有很好的描述

如果有人需要此答案的代码示例。

1.Create class 符合 ObservableObject

class Test: ObservableObject{ }

2.in AppDelegate.Swift 声明 var myVar = Test()

class AppDelegate: UIResponder, UIApplicationDelegate {
    var myVar = Test()

    //****
}

3.in SceneDelegate.swift 在 "if let windowScene = scene as? UIWindowScene {" 中更改代码如下:

if let windowScene = scene as? UIWindowScene {

    let myVar = (UIApplication.shared.delegate as! AppDelegate).myVar
    window.rootViewController = UIHostingController(rootView: contentView.environmentObject(myVar))
    self.window = window
    window.makeKeyAndVisible()

}