Reputation: 45
Try to develop login page in swift then I want to validate certain condition for error return.
from print(Error.localizeDescription) I get some return like
How to validate that condition based on Error.localizeDescription ?
Auth.auth().signIn(withEmail: email, password: pass, completion: {[weak self] result, Error in
guard let StrongSelf = self else{
return
}
if let Error = Error {
print(Error.localizedDescription)
}
guard Error == nil else{
// in here there is validation of return error (e.g. wrong password, account not exist)
self?.reasonLabel.isHidden=false
self?.reasonLabel.text=Error
return
}
self!.checkinfo()
})
Upvotes: 1
Views: 1062
Reputation: 598765
If you want to take a specific action based on the error that Firebase Authentication raises, parsing the Error.localizeDescription
is not the best way to do that. Instead check the error code
of the NSError
object you get in the completion handler again the values shown in the documentation on handling errors.
For example (based on this repo:
switch error {
case let .some(error as NSError)
where UInt(error.code) == FUIAuthErrorCode.userCancelledSignIn.rawValue:
print("User cancelled sign-in")
case .none:
if let user = authDataResult?.user {
signed(in: user)
}
}
}
Upvotes: 0
Reputation: 123
First of all you should not to declare any property capitalized, instead use lowercased or camel if need so. second if you using [weak self] and make guard let condition then use strong one to prevent retain cycle and try to do not use force unwrap.
Auth.auth().signIn(withEmail: email, password: pass, completion: {[weak self] result, error in
guard let self = self else { return }
if let error = error {
print(error.localizedDescription)
let alert = UIAlertController.configureAlertController(error.localizedDescription)
self.present(alert, animated: true)
return
}
// your logic
/* or
if let error = error {
print(error.localizedDescription)
UIAlertController. showAlert(error.localizedDescription)
}else{
// your logic
}
*/
/* or
guard let result = result else {
UIAlertController. showAlert(error?.localizedDescription ?? "unknown error")
return
}
// your logic
*/
/*
or some else, but avoid force unwrap
*/
})
Notice that your if let
statement with error check won't prevent execution of your whole code and self!.checkinfo()
will be performed, return
in the end of if let error..
will tell your method that he needs to stop
extension UIAlertController {
static func configureAlertController(with title: String = "Attention", message: String) -> (UIAlertController){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "ОК", style: .default) {(action) in}
alertController.addAction(action)
return alertController
}
}
Upvotes: 1