Reputation: 3433
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
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
Reputation: 50089
applicationDidFinishLaunching sounds like a good place for defaults
Upvotes: 2
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 createdloadView
is the code that sets up the viewAnother 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