我们现有的项目最近已更新到Firebase 5,Swift 4,我们的身份验证错误处理似乎无法正常工作。
我在SO上找到了几个答案,但那些似乎不再适用:
假设用户正在登录并输入有效的电子邮件和无效密码,这些密码将传递给以下代码进行身份验证
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是一个可选项,当选择时,编译器会显示
Enum case 'wrongPassword' is not a member of type 'AuthErrorCode?'
即使这是一个可选择的选项。
答案 0 :(得分:6)
您应该通过将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) } } }