【问题标题】:Handling Firebase 5 Authentication Errors In Swift 4在 Swift 4 中处理 Firebase 5 身份验证错误
【发布时间】:2018-11-19 08:48:46
【问题描述】:

我们有一个最近更新到 Firebase 5、Swift 4 的现有项目,但我们的身份验证错误处理似乎无法正常工作。

我在 SO 上找到了几个答案,但这些似乎不再适用:

Error Handling

Auth Codes

假设一个用户正在登录,他们输入了一个有效的电子邮件和无效的密码,它们被传递给下面的代码进行身份验证

Auth.auth().signIn(withEmail: user, password: pw, completion: { (auth, error) in
    if error != nil {
        let errDesc = error?.localizedDescription
        print(errDesc!) //prints 'The password is invalid'
        let err = error!
        let errCode = AuthErrorCode(rawValue: err._code)
        switch errCode {
        case .wrongPassword: //Enum case 'wrongPassword' not found in type 'AuthErrorCode?'
            print("wrong password")
        default:
            print("unknown error")
        }
    } else {
        print("succesfully authd")
    }
})

以前,我们可以使用 FIRAuthErrorCode 来比较可能的错误,例如 FIRAuthErrorCodeInvalidEmail、FIRAuthErrorCodeWrongPassword 等,但由于这一行的错误,上面发布的代码将无法编译

case .wrongPassword:   Enum case 'wrongPassword' not found in type 'AuthErrorCode?'

奇怪的是,如果我通过键入来使用自动填充

case AuthErrorCode.wr

.wrongPassword is a selectable option and when seleted the compiler shows

Enum case 'wrongPassword' is not a member of type 'AuthErrorCode?'

即使它是一个可选择的选项。

【问题讨论】:

    标签: swift firebase firebase-authentication


    【解决方案1】:

    您应该通过将 Error 转换为 NSError 来处理错误代码。

      Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in
        switch error {
        case .some(let error as NSError) where error.code == AuthErrorCode.wrongPassword.rawValue:
          print("wrong password")
        case .some(let error):
          print("Login error: \(error.localizedDescription)")
        case .none:
          if let user = authResult?.user {
            print(user.uid)
          }
        }
      }
    

    【讨论】:

    • 哇——我没想到会这样。如果我阅读正确,这里发生的事情是将错误转换为 NSError 并获取错误的整数代码,然后将其与从可能错误的 rawValue 派生的整数代码进行比较。很好的答案! NSError 非常不迅速,但答案非常有效。对于未来的读者:Optional<Wrapped> 类型是一个枚举,有两种情况,none 和 some(Wrapped),用于表示可能存在或不存在的值 谢谢。
    猜你喜欢
    • 2021-07-11
    • 2016-06-12
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多