尝试在swift中开发登录页面,然后我想验证错误返回的某些条件。
from print(Error.localizeDescription)我得到一些像
- 密码无效或用户没有密码
- 没有与此标识符对应的用户记录
如何验证基于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()
})
首先,您不应该声明任何属性大写,而是使用小写或驼峰字体。其次,如果您使用[弱self]并设置guard let条件,则使用强self来防止保留循环,并尽量不要使用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
*/
})
请注意,带有错误检查的if let
语句不会阻止整个代码的执行,self!.checkinfo()
将被执行,if let error..
末尾的return
将告诉您的方法他需要停止
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
}
}
如果您想根据Firebase Authentication引发的错误采取特定的操作,解析Error.localizeDescription
并不是最好的方法。相反,检查您在完成处理程序中获得的NSError
对象的错误code
,再次检查关于处理错误的文档中显示的值。
例如(基于这个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)
}
}
}