I want to switch the ViewController on load when the user is already logged in. The problem: The view didnt change when user is equal to "true"...
Thank you in advance!!
override func viewDidLoad() {
super.viewDidLoad()
var user: String?
user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String
if user == "true" {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
self.show(vc!, sender: vc)
}
// Do any additional setup after loading the view, typically from a nib.
}
Remove the code from viewDidLoad
method and use the below method.
override func viewDidAppear() {
guard let user = UserDefaults.standard.string(forKey: "loginSuccessfull"), user == "true" else {
return
}
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView")!
self.present(vc, animated: true)
}
You should put the code in which you display the second View Controller in either viewWillAppear()
or viewDidAppear()
.
override func viewDidAppear() {
super.viewDidAppear()
var user: String?
user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String
if user == "true" {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
self.show(vc!, sender: vc)
}
// Do any additional setup after loading the view, typically from a nib.
}
Reason being that during viewDidLoad()
some of the properties of your ViewController has not been defined and it is not ready to present another ViewController.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With