代码之家  ›  专栏  ›  技术社区  ›  Jay

在Swift 4中处理FireBase 5身份验证错误

  •  3
  • Jay  · 技术社区  · 7 年前

    我们有一个现有的项目,最近更新到FireBase 5、Swift 4,我们的身份验证错误处理似乎不起作用。

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

    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、firautherrorcodewronpassword等可能的错误进行比较,但由于这一点,上面发布的代码将无法编译这一行中的错误。

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

    奇怪的是,如果我用打字自动填充

    case AuthErrorCode.wr
    

    .wrong password是一个可选择的选项,选择后编译器将显示

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

    即使它是可选的。

    1 回复  |  直到 7 年前
        1
  •  6
  •   Ibrahim Ulukaya    7 年前

      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)
          }
        }
      }