简体   繁体   中英

Swift 4 Firebase Auth custom error code

I tried to define custom error codes to Firebase Auth with this code:

extension AuthErrorCode {
    var errorMessage: String {
        switch self {
        case .emailAlreadyInUse:
            return "Ezzel a névvel már létezik rendezvény"
        case .invalidEmail:
            return "Hibás formátum: Rendezvény neve. Kérlek ne használj speciális karaktereket és szóközt"
        case .userNotFound:
            return "Ezzel a névvel nem létezik rendezvény"
        case .networkError:
            return "Hálózat nem elérhető. Próbáld meg később"
        case .weakPassword:
            return "A jelszó túl gyenge. Legalább 6 karakter hosszúnak kell lennie."
        case .wrongPassword:
            return "Hibás jelszó"
        default:
            return "Unknown error occurred"
        }
    }
}

And after reach this codes in checkLogin() method:

func checkLogin(){
if eventNameTextField.text != "" && passwordTextField.text != "" {
    let eventname = eventNameTextField.text! + "@somemail.com"

    Auth.auth().signIn(withEmail: eventname, password: passwordTextField.text!, completion: { (user, error) in
        if user != nil {
            self.performSegue(withIdentifier: "goToMain", sender: self)
        }
        else{
            if let myError = AuthErrorCode(rawValue: (error?._code)!) {
                self.errorLabel.text = myError.errorMessage
                print(myError.errorMessage)
            }
        }
    })
}
else {
    self.errorLabel.text = "A mezők kitöltése kötelező"
}
}

If I try to create a new user, it's work perfectly, but when I try to login with wrong password (or with invalid username), it says

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

to self.errorLabel.text = myError.errorMessage

https://i.stack.imgur.com/HGqov.png

If I remove the label, it's working perfectly and show me the error code in the console.

Your errorLabel is nil. As a result, when you try to assign myError.errorMessage to errorLAbel.text it crashes. The problem with your current code is that the errorLabel is not instantiated when you access its text value.

When you create a new user your app works because you don't assign anything to errorLabel .

From your snapshot I'm assuming you are using xib or storyboard. Then errorLabel is not connected with @IBOutlet connect this. You are accessing label before initialisation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM