Mar*_*iah 16 error-handling ios firebase swift firebase-authentication
我正在尝试使用swift和firebase在iOS项目中创建用户按钮时添加错误处理:
这是按钮的代码:
@IBAction func Register(sender: AnyObject) {
if NameTF.text == "" || EmailTF.text == "" || PasswordTF.text == "" || RePasswordTF == "" || PhoneTF.text == "" || CityTF.text == ""
{
let alert = UIAlertController(title: "?????", message:"??? ???? ???? ?? ?????? ????????", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "???", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
} else {
if PasswordTF.text != RePasswordTF.text {
let alert = UIAlertController(title: "?????", message:"????? ?????? ??? ?????????", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "???", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
} else {
FIRAuth.auth()?.createUserWithEmail(EmailTF.text!, password: PasswordTF.text!, completion: { user, error in
print(error)
if error != nil {
let errorCode = FIRAuthErrorNameKey
switch errorCode {
case "FIRAuthErrorCodeEmailAlreadyInUse":
let alert = UIAlertController(title: "?????", message:"??????? ??????", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "???", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
case "FIRAuthErrorCodeUserNotFound":
let alert = UIAlertController(title: "?????", message:"???????? ??? ?????", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "???", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
case "FIRAuthErrorCodeInvalidEmail":
let alert = UIAlertController(title: "?????", message:"??????? ??? ????", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "???", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
case "FIRAuthErrorCodeNetworkError":
let alert = UIAlertController(title: "?????", message:"??? ?? ??????? ?????????", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "???", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
default:
let alert = UIAlertController(title: "?????", message:"??? ??? ?????", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "???", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
} else {
FIRAuth.auth()?.signInWithEmail(self.EmailTF.text!, password: self.PasswordTF.text!, completion: { (user: FIRUser?, error: NSError?) in
if let error = error {
print(error.localizedDescription)
} else {
self.ref.child("UserProfile").child(user!.uid).setValue([
"email": self.EmailTF.text!,
"name" : self.NameTF.text!,
"phone": self.PhoneTF.text!,
"city" : self.CityTF.text!,
])
print("Sucess")
// self.performSegueWithIdentifier("SignUp", sender: nil)
}
})
} //else
})
} //Big else
} //Big Big else
}
}//end of
Run Code Online (Sandbox Code Playgroud)
我不确定switch语句中的错误语法是否正确!
因为当我在模拟器中测试它时它总是给我一个未知错误的defualt案例!+我在文档中找不到语法:https: //firebase.google.com/docs/auth/ios/errors
那么,使用新的firebase和swift添加错误处理的正确语法是什么!
小智 32
我实际上只是在相当长的一段时间内努力解决这个问题.我已经尝试了上面的答案中发布的代码,error.code行给了我一个错误.它确实与error._code一起使用.换句话说,对保罗的原始答案有一点点修改.这是我的最终代码(我将编辑所有错误):
if let errCode = FIRAuthErrorCode(rawValue: error!._code) {
switch errCode {
case .errorCodeInvalidEmail:
print("invalid email")
case .errorCodeEmailAlreadyInUse:
print("in use")
default:
print("Create User Error: \(error)")
}
}
Run Code Online (Sandbox Code Playgroud)
Shr*_*kar 16
更新了Swift 4 + Firebase 4 + UIAlertController
extension AuthErrorCode {
var errorMessage: String {
switch self {
case .emailAlreadyInUse:
return "The email is already in use with another account"
case .userNotFound:
return "Account not found for the specified user. Please check and try again"
case .userDisabled:
return "Your account has been disabled. Please contact support."
case .invalidEmail, .invalidSender, .invalidRecipientEmail:
return "Please enter a valid email"
case .networkError:
return "Network error. Please try again."
case .weakPassword:
return "Your password is too weak. The password must be 6 characters long or more."
case .wrongPassword:
return "Your password is incorrect. Please try again or use 'Forgot password' to reset your password"
default:
return "Unknown error occurred"
}
}
}
extension UIViewController{
func handleError(_ error: Error) {
if let errorCode = AuthErrorCode(rawValue: error._code) {
print(errorCode.errorMessage)
let alert = UIAlertController(title: "Error", message: errorCode.errorMessage, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
print(error!._code)
self.handleError(error!) // use the handleError method
return
}
//successfully logged in the user
})
Run Code Online (Sandbox Code Playgroud)
尽管已经正确回答了这个问题,但我想为此分享一个很好的实现,我们将其添加到我们的项目中.
这也可以用于其他错误类型,但我们只需要FIRAuthErrorCodes.
如果您将FIRAuthErrorCode扩展为具有string类型的变量errorMessage,则可以为用户提供自己的错误消息:
extension FIRAuthErrorCode {
var errorMessage: String {
switch self {
case .errorCodeEmailAlreadyInUse:
return "The email is already in use with another account"
case .errorCodeUserDisabled:
return "Your account has been disabled. Please contact support."
case .errorCodeInvalidEmail, .errorCodeInvalidSender, .errorCodeInvalidRecipientEmail:
return "Please enter a valid email"
case .errorCodeNetworkError:
return "Network error. Please try again."
case .errorCodeWeakPassword:
return "Your password is too weak"
default:
return "Unknown error occurred"
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以自定义上面的一些,并将其余部分分组为"未知错误".
使用此扩展,您可以处理错误,如Vladimir Romanov的回答所示:
func handleError(_ error: Error) {
if let errorCode = FIRAuthErrorCode(rawValue: error._code) {
// now you can use the .errorMessage var to get your custom error message
print(errorCode.errorMessage)
}
}
Run Code Online (Sandbox Code Playgroud)