Search code examples
swiftxcodecustomizationmessage

How can I customize the error message with localizedDescription?


I have created a login and sign up page for my app. Everything is running smoothly, but I want to be able to customize the error messages when the user enters an incorrect email address or password. This is my code right now:

            // Signing in the user
            Auth.auth().signIn(withEmail: email, password: password) { (result, error) in

                if error != nil {

                    // Couldn't sign in
                    self.loginErrorLabel.text = error!.localizedDescription
                    self.loginErrorLabel.alpha = 1
                }
                else {

                    let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController

                    self.view.window?.rootViewController = homeViewController
                    self.view.window?.makeKeyAndVisible()
                }
            }

When a user enters a non-existant/incorrect email or password, an error label appears, saying "The password is invalid or the user does not have a password."

Instead, I want it to return with: "The username or password you entered is incorrect." Is there a way to do this without completely changing the code, such as just adding some code beforehand to indicate what localizedDescription is? All help is welcome, thanks so much!


Solution

  • you can do something like this

     let userInformation = [NSLocalizedDescriptionKey: "your error message"]
     let error = NSError(domain: "your domain", code: 401, userInfo:userInformation)
    

    now you can use that error with "localizedDescription" or as "Error"