I try to get an error code from FirebaseAuth and show something dependent on the error code. I try to do this with a switch:
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
if let error = error as? AuthErrorCode {
switch error {
case .emailAlreadyInUse:
Utility.showAlertView(with: "Email already used", and: "Please choose a different email adress", in: self)
case .invalidEmail:
Utility.showAlertView(with: "Email is invalid", and: "Please enter a valid email", in: self)
case .weakPassword:
Utility.showAlertView(with: "Weak Password", and: "Please Choose a longer Password", in: self)
default:
break
}
} else {
}
}
But I get a warning:
Cast from 'Error' to unrelated type 'AuthErrorCode' always fails
I dont know what's to do. Thanks for your time, Boothosh
I combined code from multiple answers to get the following working in Firebase 10.2.0.
Note that the way to convert the returned error to something usable in the switch statement is:
AuthErrorCode.Code.init(rawValue: error.code)
Auth.auth().createUser(withEmail: emailTxt, password: passwordTxt) { authResult, error in
if let error = error as? NSError {
if let errCode = AuthErrorCode.Code.init(rawValue: error.code) {
switch errCode {
case .operationNotAllowed:
// Error: The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.
print("error: operationNotAllowed")
case .emailAlreadyInUse:
// Error: The email address is already in use by another account.
print("error: emailAlreadyInUse")
case .invalidEmail:
// Error: The email address is badly formatted.
print("error: invalidEmail")
case .weakPassword:
// Error: The password must be 6 characters long or more.
print("error: weakPassword")
default:
print("Error: \(error.localizedDescription)")
}
}
} else {
print("User signed up successfully")
let newUserInfo = Auth.auth().currentUser
}
}
According to Firebase documentation AuthErrorCode
is int enum so you cannot cast Error into it. Instead you need to use the error's code and try to create an instance of AuthErrorCode
with it:
let code = (error as NSError).code
if let code = AuthErrorCode(rawValue: code) {
switch code {
case .emailAlreadyInUse:
Utility.showAlertView(with: "Email already used", and: "Please choose a different email adress", in: self)
case .invalidEmail:
Utility.showAlertView(with: "Email is invalid", and: "Please enter a valid email", in: self)
case .weakPassword:
Utility.showAlertView(with: "Weak Password", and: "Please Choose a longer Password", in: self)
default:
break
}
}
Update
For optional error you need to unwrap it before using its code:
if let err = error as NSError?, let code = AuthErrorCode(rawValue: err.code) {
switch code {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With