[英]show() View Controller doesn't work
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.
我首先读取保存在UserDefaults中的值,以了解它们是否已登录,如果没有,我想显示ViewController来允许他们登录。
But anyway, the LogInViewController won't show, this is my code : 但是无论如何,LogInViewController不会显示,这是我的代码:
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 我也尝试了没有'if'条件,它不再起作用
EDIT : I also tried presentVC() and I had the error "Attempt to present on whose view is not in the window hierarchy" 编辑:我也尝试了presentVC(),并且出现错误“尝试在其视图不在窗口层次结构中进行呈现”
Thanks for help 感谢帮助
You are trying to login in the MainViewController
. 您正在尝试登录
MainViewController
。 You should avoid when possible managing your login in a view controller. 您应尽可能避免在视图控制器中管理登录名。 The login is more effective if managed in your
AppDelegate
. 如果在
AppDelegate
管理,则登录更为有效。
Add this code to didFinishLaunchingWithOptions
in AppDelegate.swift 将此代码添加到
didFinishLaunchingWithOptions
中的didFinishLaunchingWithOptions
中
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
. 确保您可以访问
UserDefaults
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.