使用完成处理程序来处理来自firebase

时间:2017-02-15 23:12:07

标签: ios firebase swift3 firebase-authentication

我试图实现一个完成处理程序来处理从我对firebase的调用返回的结果。截至目前,当我调用该函数时,它会直接跳转到completionHandler(result!)并返回nil。我做错了什么?

//View Controller

FireChangePassword(email: (User.current?.email)!, currentPassword: currentPassword!, newPassword: newPassword!, completionHandler: { (result) -> Void in

    if result == ChangePasswordResult.AuthError{
        errorLabel.text = "Incorrect Passworld"
    }
    else if result == ChangePasswordResult.FBError{
        errorLabel.text = "System Error"
    } 
    else if result == ChangePasswordResult.Success{
        _ = self.navigationController?.popToRootViewController(animated: true)
     }
})

//Firebase.swift

enum FirebaseErrors:Error {
        case AuthError
        case FBError
        case Success   
}

typealias CompletionHandler = (_ result:ChangePasswordResult) -> Void

func FireChangePassword(email: String, currentPassword: String, newPassword: String, completionHandler: CompletionHandler) {

    let user = FIRAuth.auth()?.currentUser
    let credential = FIREmailPasswordAuthProvider.credential(withEmail: email, password: currentPassword)
    var result : ChangePasswordResult?


    user?.reauthenticate(with: credential) { error in
        if let error = error {
            // An error happened.
            print("Firebase ReAuthentication Error")
            print(error)

            result = ChangePasswordResult.AuthError

        } else {
            // User re-authenticated.
            FIRAuth.auth()?.currentUser?.updatePassword(newPassword) { (error) in
                if error == nil {
                    print("Firebase Change Password Successful")
                    result = ChangePasswordResult.Success

                }
                else {
                    print(error!)
                    print("Firebase Change Password Failed")
                    result = ChangePasswordResult.FBError
                }

            }
        }
    }

    completionHandler(result!)

}

1 个答案:

答案 0 :(得分:0)

这是一个简化的更改密码流程。

假设用户正在查看带有密码文本字段的viewController,用户可以在其中键入更新的密码。

他们输入一个新密码,然后点按“更改”状态。按钮 - 然后该按钮调用此代码:

class ViewController: UIViewController {

  @IBAction func buttonAction(_ sender: Any) {

      let user = FIRAuth.auth()?.currentUser
      let updatedPassword = self.passwordField.text
      user?.updatePassword(updatedPassword, completion: {  error in
         if error != nil {
           print("Error. Show error in current viewController")
         } else {
           print("Login Successful, go to next viewController")
         }
      })
   }