Learn Courses My Dashboard

How to set UserDefaults first time view renders?

Hi All,

I have this super simple code, where I want the userDefault to be set to a value and then displayed immediately.
The problem is that the UserDefault is set the SECOND time the view renders. So how can i fix this problem?

  var body: some View {
        VStack{
            
            Text(UserDefaults.standard.string(forKey: "stringTester") ?? "Could not")

        }.onAppear{
            UserDefaults.standard.set("UserDefualt is not set", forKey: "stringTester")
        }
    }

Set the value in your View's init method.

So it worked using init() but only for the code i attached before.
I have the same problem when i try to do it like this, any ideas?:

getDocument is asynchronous, so your init method continues before getDocument sets the value in UserDefaults. Since this value isn’t being stored in a way that SwiftUI is observing, it doesn’t trigger a redraw when the value changes.

If you are targeting iOS 14+, think about using the @AppStorage property wrapper to set a default value when your View is created and then observe changes to the value in UserDefaults.

If you have to support iOS 13, then you will need to assign the value to a state variable for observation.