I'm having trouble figuring out how to save data in my SwiftUI @EnvironmentObject
instance. I created an instance of my @EnvironmentObject
type, UserData
, in my SceneDelegate
file, which then gets passed into my root view which is then accessed and modified by my other views.
My question is, how would one save the data in such an instance for access after the user closes and re-opens the app?
For example, I have a hasDoneSetup
property in my UserData
instance which defaults to false, so that my first-time setup sequence runs only the first time the app is opened. The setup sequence disappears when the setup is completed, which is correct and working fine. However, when I close and re-open the app, it seems that a new UserData
instance is being made, as the setup sequence runs again.
Here's some of my SceneDelegate
code:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// Other properties omitted
var userData = UserData()
// Other code omitted
// Use a UIHostingController as window root view controller
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
// This line is where I pass the UserData instance to my root view.
// I don't want to pass a new instance each time the app is opened however.
// Rather, I want to make a new instance only the first time the app is opened, and use that instance anytime the app is opened henceforth.
window.rootViewController = UIHostingController(rootView: MainScreen().environmentObject(userData))
self.window = window
window.makeKeyAndVisible()
// Other code omitted
}
I would greatly appreciate any and all help! Thank you so much in advance and I hope you have a great day! :)