0

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.

1
  • 1
    It is hard to help without any code, can you please show the code you used and where to get/set the UserDefaults? Commented May 31, 2018 at 20:40

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense now! Thanks!
0

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...

1 Comment

Awesome! Thanks for this, exactly what I searched for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.