【问题标题】:Handling Errors in New Firebase and Swift处理新 Firebase 和 Swift 中的错误
【发布时间】:2016-12-27 12:10:34
【问题描述】:

我正在尝试在使用 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

我不确定switch语句中的错误语法是否正确!

因为当我在模拟器中测试它时,它总是给我默认情况,这是未知错误! + 我在文档中找不到语法: https://firebase.google.com/docs/auth/ios/errors

那么,使用新的 firebase 和 swift 添加错误处理的正确语法是什么!

【问题讨论】:

  • 旁注 - 你不应该使用大的 if-else 语句。它们在您的代码中可能真的很混乱。只需执行以下操作:if NameFT.text == "" ... { return } 通过添加return,您将停止进一步执行。更多信息,请查看this SO question

标签: ios swift error-handling firebase firebase-authentication


【解决方案1】:

实际上,我已经为此苦苦挣扎了很长时间,并发现了问题所在。我已经尝试了上面答案中发布的代码,error.code 行给了我一个错误。它确实适用于error._code。换句话说,对保罗的原始答案稍作修改。这是我的最终代码(我会针对所有错误进行编辑):

if let errCode = AuthErrorCode(rawValue: error!._code) {

    switch errCode {
        case .errorCodeInvalidEmail:
            print("invalid email")
        case .errorCodeEmailAlreadyInUse:
            print("in use")
        default:
            print("Create User Error: \(error)")
    }    
}

【讨论】:

  • 在您发布答案之前!正如您发布的那样,我已经更新了我的代码,它运行良好!还是谢谢你!
  • 太棒了!我看了这么多资源,只提到你可以处理这些错误,但没有解释如何,我以为我终于得到了我的代码。
  • 请注意,在 Swift 3 中,我需要将 Error 桥接到 NSError,以便暴露 .code,即。 if let error = error as NSError? ...
【解决方案2】:

为 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)

        }
    }

}

使用示例:

    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

    })

【讨论】:

  • 很好的答案!适用于 Swift 4.2 和 Firebase 5.2.0。我会在代码中做的唯一改进是使用“ if let error = error { // user error in here without the force unwrap (!) }”安全地解开可选项。结果是一样的,但是伙计,那个爆炸算子! :)
【解决方案3】:

尽管这已被正确回答,但还是想分享一个我们添加到项目中的不错的实现。

这也可以用于其他错误类型,但我们只需要它用于FIRAuthErrorCodes

如果您将 FIRAuthErrorCode 扩展为具有字符串类型的变量 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"
        }
    }
}

您可以像我们上面那样只自定义一些,并将其余的分组在“未知错误”下。

使用此扩展程序,您可以处理 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)
    }
}

【讨论】:

  • @Cesare 在我身边工作。介意分享更多代码吗?
【解决方案4】:

FIRAuthErrorCode 是一个 int 枚举而不是一个字符串枚举。执行以下操作:

if let error = error {
        switch FIRAuthErrorCode(rawValue: error.code) !{
                case .ErrorCodeInvalidEmail:

更多信息请参阅answer

【讨论】:

    【解决方案5】:

    我正在使用 Swift 5 和 Firebase 6.4.0,对我来说,以上都没有真正奏效。经过一番尝试,我想出了这个:

    Auth.auth().createUser(withEmail: emailTextfield.text!, password: passwordTextfield.text!) { (user, error) in
            if error!= nil{
    
                    let alert = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
                    alert.addAction(okAction)
                    self.present(alert,animated: true)
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-18
      • 2017-03-21
      • 2015-02-21
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2016-12-14
      相关资源
      最近更新 更多