读取Firebase身份validation错误(Firebase 3.x和Swift)

我无法弄清楚如何在新版本的Firebase中读取FIRAuthErrorNameKey。 以下是我到目前为止,但“let errorCode = FIRAuthErrorNameKey”行是​​不正确的。 从阅读Firebase文档,我也尝试访问userInfo中的错误代码,但没有成功,没有想法。

// Send request to Firebase to add user to register user FIRAuth.auth()?.createUserWithEmail(emailTextField.text!, password: passwordTextField.text!, completion: { (user, error) in // Check for errors and respond to user accordingly. if error != nil { let errorCode = FIRAuthErrorNameKey switch errorCode { case "FIRAuthErrorCodeEmailAlreadyInUse": // Add logic accordingly case ...: // Add logic accordingly case default: // Add logic accordingly } } }) 

尝试这个。 这对我有用。 此外,粘贴到您的项目后。 如果您需要查看所有的FIRAuthErrorCode代码。 将鼠标hover在.ErrorCodeInvalidEmail然后按鼠标左键,它会显示其余的内容。

如果您有任何问题,请告诉我,并尽力帮助您。 祝你好运!

  FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in if error != nil { if let errCode = FIRAuthErrorCode(rawValue: error!._code) { switch errCode { case .ErrorCodeInvalidEmail: print("invalid email") case .ErrorCodeEmailAlreadyInUse: print("in use") default: print("Create User Error: \(error!)") } } } else { print("all good... continue") } } 

没有一个答案似乎是最新的,这是我目前在Swift 3.x,FirebaseAuth 4.0.0

 Auth.auth().signIn(withEmail: email, password: password) { (user, error) in if let error = error as NSError? { guard let errorCode = AuthErrorCode(rawValue: error.code) else { print("there was an error logging in but it could not be matched with a firebase code") return } switch errorCode { case .invalidEmail: print("invalid email") //... 

Firebase已经改变了一些代码,如果您是Firebase的新手,则需要一些时间让代码正常工作。 我已经花了近3个小时搞清楚发生了什么事情。 现在看起来如何:

 Auth.auth().createUser(withEmail: email, password: password) { (user: User?, error) in if error != nil { // Handle the error (ie notify the user of the error) if let errCode = AuthErrorCode(rawValue: error!._code) { switch errCode { case .invalidEmail: print("invalid email") case .emailAlreadyInUse: print("in use") default: print("Other error!") } } } 

从代码片段看来,您正在尝试使用错误代码,而不是交换机中的FIRAuthErrorNameKey。 在这种情况下,你想要使用的是在callback中返回的NSError对象的错误代码。 使用:

 let errorCode = error.code 

这样,您的errorCodevariables将包含返回的错误代码,您可以继续处理error handling逻辑。

我不知道这是否有帮助,但你也可以这样做:

 let errcode = FIRAuthErrorCode(rawValue: error!._code) if errcode == FIRAuthErrorCode.errorCodeRequiresRecentLogin{ //do error handling here }