如何在Firebase身份验证中正确使用addStateDidChangeListener?

时间:2018-03-25 13:27:36

标签: ios swift firebase firebase-authentication

我正在尝试创建registerVC,在用户填写文本字段后,按下注册按钮我尝试使用Firebase身份验证创建用户,

Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
  // ...
}

这是按下注册按钮时的代码

@IBAction func signUpButtonDidPressed(_ sender: Any) {
        print("000")
        SVProgressHUD.show(withStatus: "Harap Tunggu")

        print("a")

        userEmail = emailTextField.text!
        userPassword = passwordTextField.text!

        print("b")

        Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
            print("c")


            print("d")



            if let user = user {
                print("e")

                user.sendEmailVerification(completion: { (error) in
                    print("f")
                    print("g")


                    let fullName = "\(self.firstNameTextField.text!) \(self.lastNameTextField.text!)"
                    let emailOfTheUser = "\(self.emailTextField.text!)"

                    print("h")

                    let userKMViaEmail = UserKM(uid: user.uid, fullname: fullName, email: emailOfTheUser )

                    print("i")


                    print("111")

                    // save user basic information in NSUserDefault
                    self.saveUserKMBasicDataInUserDefault(userKM: userKMViaEmail)
                     print("2222")

                    self.showAlert(alertTitle: "BErhasil", alertMessage: "email dikirim", actionTitle: "OK")

                    // the user need to read the alert first, after tap the action the user will be moved to LoginUsingEmailVC
//                    self.showCustomAlert(alertTitle: "Periksa Email Anda!", alertMessage: "Assalamualaikum, Mohon Ikuti link yang ada pada email yang kami kirimkan. Harap tunggu 15-30 menit apabila email kami belum juga sampai.", actionTitle: "Login")
//
                     print("3333")
                    SVProgressHUD.dismiss()

                     print("444")

                })
            }

        }




    }

在app delegate中,我编写代码来判断用户是否已经登录时用户是否会直接进入Main Tab Bar,否则用户将在应用程序启动时被发送到Welcome Screen VC。

这是我的App Delegate中的代码。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


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

        FirebaseApp.configure()
        checkUserLogin()


        // to track the user default info.plist location in the device (simulator) for checking purpose.
        print("The Location of info.plist of User Default: \(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String)")


        return true
    }

}




extension AppDelegate {

    // MARK: - HELPER METHODS

    func checkUserLogin() {
        // to check whether the user has already logged in or not


        SVProgressHUD.show()
        Auth.auth().addStateDidChangeListener { (auth, user) in

            if user == nil {
                SVProgressHUD.dismiss()
                self.goToWelcomeVC()
            } else {
                SVProgressHUD.dismiss()
                self.goToMainTabBar()
            }

            // if user is not nil then automatically go to maintab bar (initialVC is indeed main tab bar controller)
            SVProgressHUD.dismiss()
        }
    }



    func goToMainTabBar () {
         print("XXXXXXXX")
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let mainTabBar = storyboard.instantiateViewController(withIdentifier: "mainTabBar")
        window?.rootViewController = mainTabBar

    }

    func goToWelcomeVC () {
        let storyboard = UIStoryboard(name: "Welcome", bundle: nil)
        let login = storyboard.instantiateViewController(withIdentifier: "WelcomeVC")
        window?.rootViewController = login

    }


}

这是我的调试区域中的打印结果,我们可以看到位于AppDelegate中的XXXXX是自动触发的。

enter image description here

我们可以看到,在按下注册按钮后,Auth.auth().createUser()被触发了。当Auth.auth().createUser()被触发时,AppDelegate中的Auth.auth().addStateDidChangeListener也会被触发。

但不幸的是,当AppDelegate中的Auth.auth().addStateDidChangeListener被触发时,它会让我的应用自动转到主标签栏。

此时,我希望我继续留在SignUpVC上,而不是MainTabBarVC。

也许我在编写下面的代码时会犯错误,因为当激活createUser()时,addStateDidChangeListener()中的用户基本上不再是nil。

Auth.auth().addStateDidChangeListener { (auth, user) in

            if user == nil {
                SVProgressHUD.dismiss()
                self.goToWelcomeVC()
            } else {
                SVProgressHUD.dismiss()
                self.goToMainTabBar()
            }

            // if user is not nil then automatically go to maintab bar (initialVC is indeed main tab bar controller)
            SVProgressHUD.dismiss()
        }

但是如果他们已经登录,我也希望用户在MainTab栏中,否则如果他们还没有登录则转到欢迎屏幕?

0 个答案:

没有答案