我不熟悉Swift,我正在使用FireBase功能开发我的应用程序。
我遵循了FireBase文档中的过程,并成功地正常实现了身份验证控制器,除了一个我觉得奇怪的细节。当用户已经通过身份验证时,它会在转到主控制器之前大约半秒显示loginviewcontroller。对吗?
如果用户已经登录,我希望应用程序直接转到主控制器。谢谢您。
遵循准则:

class LoginViewController: UIViewController {

@IBOutlet weak var textFieldPassword: UITextField!
@IBOutlet weak var textFieldEmail: UITextField!

var authStateListener: AuthStateDidChangeListenerHandle?

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    authStateListener = Auth.auth().addStateDidChangeListener { (auth, user) in
        if user != nil {
            self.callMainController()
        }
    }
}

func callMainController() {
    if let storyboard = self.storyboard {
        let viewController = storyboard.instantiateViewController(withIdentifier: "MainController") as! UITabBarController
        self.present(viewController, animated: true, completion: nil)
    } else {
        Alert(controller: self).show(message: "Error on show MainController")
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    Auth.auth().removeStateDidChangeListener(authStateListener!)
}

@IBAction func didTapLogin(_ sender: Any) {
    if let email = self.textFieldEmail.text, let password = self.textFieldPassword.text {
        Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
            if let error = error {
                print(error.localizedDescription)
                return
            }
            print("User Logged")
        }
    }
}

最佳答案

您应该检查AppDelegate中的登录状态,并在didFinishLaunchingWithOptions函数中设置rootviewcontroller。

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()

        var initialViewController: UIViewController!

        if Auth.auth().currentUser == nil {
          initialViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainViewController")//replace your mainviewcontroller identifier
        } else {
          initialViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController")//replace your loginviewcontroller identifier
        }

        window?.rootViewController = initialViewController
        window?.makeKeyAndVisible()

        return true
      }

关于swift - 当用户已经过身份验证时,它会在进入MainController之前显示LoginViewController大约半秒钟,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46427968/

10-10 01:00