Hyung Duc Da
Hyung Duc Da

Reputation: 41

Setting global variables with UserDefaults

I'm relatively new into this and tried a little bit of code, but encountered a problem.

In my App I have a global variable which keeps track wether a user chose his username already or not. Once he has picked his name I want to set this variable permanently to true so I can disable the segue which leads to the Username ViewController.

But I can't preset the variable since the code would re-initialize the variable everytime I re-open the app. And I still got my problems setting it up with UserDefaults.

I hope I was able to explain my problem more or less.

Upvotes: 0

Views: 1858

Answers (2)

Ajay saini
Ajay saini

Reputation: 2470

Set a bool value to userDefault

UserDefaults.standard.setBool(true, forKey: "is_userName") 

And retrieve the value for checking

if UserDefaults.standard.bool(forKey: "is_userName") {
      // User have created username 
} else {
      // Go to set username screen
}

Upvotes: 1

Popmedic
Popmedic

Reputation: 1871

UserDefaults getters will return nil if it is not set, so you don't need to set a bool, just check if the value has been set like so:

if let username = UserDefaults.standard.string(forKey:"username") {
    // user has created username, and username has the unwrapped value in it
} else {
    // go to set username screen
}

Make sure that after they go to the set username screen you set the username key in the UserDefaults:

UserDefaults.standard.string(value, forKey:"username")

Where value is the value they entered.

If you want to reset a value in the UserDefaults (i.e. they log out) use the removeObject function:

UserDefaults.standard.removeObject(forKey:"username")

That will make it so UserDefaults.standard.string(forKey:"username") will return nil again.

Adding a bool for checking will just make one more cog that can screw it all up if you forget to set it...

Upvotes: 0

Related Questions