Edward Hasted
Edward Hasted

Reputation: 3433

What runs before viewDidLoad?

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?

Upvotes: 4

Views: 12909

Answers (4)

Skadoosh
Skadoosh

Reputation: 171

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.

Upvotes: 0

Daij-Djan
Daij-Djan

Reputation: 50089

applicationDidFinishLaunching sounds like a good place for defaults

Upvotes: 2

user23743
user23743

Reputation:

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.

Upvotes: 3

baliman
baliman

Reputation: 620

Try it in your AppDelegate of your app

Upvotes: 0

Related Questions