iOS: Use a boolean in NSUserDefaults

Viewed 61022

When the rootViewController of my application is loaded, I want to be able to check whether or not the users login credentials have been saved to NSUserDefaults.

Basically, when the user loads the application and he/she doesn't have her login credentials saved, a modalAlertView will be pushed and the user will be able to save their credentials appropriately. This saves those UITextField strings to a respective NSUserDefault object. However, is it possible, that when this saving is done, I can create an NSUserDefault object which is a boolean and change the value to a yes?

Meaning that the boolean is already set to no, and when the user saves their login credentials, it also changes the boolean to a yes?

6 Answers

Swift 2.3

To store values

    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "logged_in") 

For fetching values

  if NSUserDefaults.standardUserDefaults().boolForKey("logged_in") == true {
      dashboardScreen()
  }else {
      loginScreen()
  }

Swift 3.0

To store values

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

to retrieve values

  UserDefaults.standard().bool(forKey: "logged_in"){
      dashboardScreen()
  }else {
      loginScreen()
  }
Related