I try to authenticate the user of my app if they are not. I first read the value saved in UserDefaults to know if they are logged in, and if not, I want to show the ViewController to allow them to log in.
But anyway, the LogInViewController won't show, this is my code :
import UIKit
import MapKit
class MainViewController: UIViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if(!UserDefaults.standard.bool(forKey: "userIsConnected")){
let LogVC = self.storyboard?.instantiateViewController(withIdentifier: "LogInViewController") as! LogInViewController
show(LogVC, sender: self)
}
}
I also tried without the 'if' condition, and it doesn't work anymore
EDIT : I also tried presentVC() and I had the error "Attempt to present on whose view is not in the window hierarchy"
Thanks for help
You are trying to login in the MainViewController
. You should avoid when possible managing your login in a view controller. The login is more effective if managed in your AppDelegate
.
Add this code to didFinishLaunchingWithOptions
in AppDelegate.swift
if !UserDefaults.standard.bool(forKey: "userIsConnected") {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let loginViewController = storyboard.instantiateViewController(withIdentifier: "LogInViewController")
window?.makeKeyAndVisible()
window?.rootViewController?.present(loginViewController, animated: true, completion: nil
}
Make sure you can access UserDefaults
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.