简体   繁体   English

SwiftUI:从 AppDelegate 访问 @EnvironmentObject

[英]SwiftUI: Access @EnvironmentObject from AppDelegate

I want to use the applicationWillTerminate function to save some user defaults before the app closes.我想使用applicationWillTerminate函数在应用程序关闭之前保存一些用户默认值。 The data I want to save is stored in an EnvironmentObject .我要保存的数据存储在EnvironmentObject 中

How can I access it from the AppDelegate class?如何从AppDelegate类访问它?

An @EnvironmentObject doesn't need to be instantiated directly in your SwiftUI objects; @EnvironmentObject不需要直接在 SwiftUI 对象中实例化; rather, it can be allocated somewhere else (for example, your UISceneDelegate) and then passed through using the .environment(…) function.相反,它可以分配到其他地方(例如,您的 UISceneDelegate),然后使用.environment(…)函数传递。

You could also allocate it on your AppDelegate, and pass that object though to your views in UISceneDelegate.scene(_:willConectTo:options:) method.您也可以在 AppDelegate 上分配它,然后将该对象传递给UISceneDelegate.scene(_:willConectTo:options:)方法中的视图。

Paul Hudson has a good description of all of this at https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views Paul Hudson 在https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views 上对所有这些进行了很好的描述

In case someone needs code example for this answer.如果有人需要此答案的代码示例。

1.Create class that conforms to ObservableObject 1.创建符合ObservableObject的类

class Test: ObservableObject{ }

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

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

    //****
}

3.in SceneDelegate.swift in "if let windowScene = scene as? UIWindowScene {" change the code like this : 3.在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()

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM