4

I need to set and store some NSUserDefaults data that can be used withing a View. This doesn't work using viewDidLoad.

Can this be done? What method could I use before viewDidLoad? What would you recommend?

Edward Hasted
  • 3,201
  • 8
  • 30
  • 48

4 Answers4

3

There are a couple of methods on UIViewController that will definitely get run before viewDidLoad - which is the appropriate place for your code depends on your specific problem and architecture.

  • initWithNibName:bundle: is called when the view controller is created
  • loadView is the code that sets up the view

Another option is to ensure that the defaults are set up by a different component, before your view controller is even initialised. That could be in the view controller of a preceding part of the workflow, or initialised by the application delegate.

  • I had tried initWithNibView beforehand but it didn't seem to work. – Edward Hasted Nov 18 '12 at 21:07
  • `awakeFromNib` is only called if your view is loaded from a NIB - not if you override `loadView` and create the views in code. If you're happy that this will always be true for your app, then it's a fine solution. –  Nov 21 '12 at 18:15
2

applicationDidFinishLaunching sounds like a good place for defaults

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • 1
    I'm sure your right but can you push me in the right direction with the detail. Do I put this in my Launch View .m? Or if I put it in the launchAppDelegate can you spell it out as it's new territory for me. – Edward Hasted Nov 18 '12 at 21:06
0

Try it in your AppDelegate of your app

baliman
  • 588
  • 2
  • 8
  • 27
0

This is an example to persist the login state of the application using UserDefaults:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // You can keep your Google API keys here(if you have any)
    let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let homeScreen = storyBoard.instantiateViewController(withIdentifier: "YourHomecontroller") as? ViewController
    if(UserDefaults.standard.isLoggedIn()){
        self.window?.rootViewController = homeScreen
    }else{
        let loginScreen = storyBoard.instantiateViewController(withIdentifier: "LoginViewController")
        self.window?.rootViewController = loginScreen
    }
    return true
}

And extend UserDefaults with these methods:

// this is used to serialize the boolean value:isLoggedIn
func setIsLoggedIn(value:Bool){
        setValue(value, forKey: "isLoggedIn")
        UserDefaults.standard.synchronize()
    }

// this method is used to check the value for isLoggedIn flag
func isLoggedIn() -> Bool{
        return bool(forKey: "isLoggedIn")
    }

this way, you can switch between the view controllers conditionally. if user is authenticated already you would want to show the home screen.

Skadoosh
  • 141
  • 1
  • 10