I want to use the applicationWillTerminate function to save some user defaults before the app closes. The data I want to save is stored in an EnvironmentObject.
How can I access it from the AppDelegate class?
I want to use the applicationWillTerminate function to save some user defaults before the app closes. The data I want to save is stored in an EnvironmentObject.
How can I access it from the AppDelegate class?
An @EnvironmentObject doesn't need to be instantiated directly in your SwiftUI objects; rather, it can be allocated somewhere else (for example, your UISceneDelegate) and then passed through using the .environment(…) function.
You could also allocate it on your AppDelegate, and pass that object though to your views in UISceneDelegate.scene(_:willConectTo:options:) method.
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
In case someone needs code example for this answer.
1.Create class that conforms to ObservableObject
class Test: ObservableObject{ }
2.in AppDelegate.Swift declare 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 :
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()
}