Yeah Yeah - 19 days ago 9
Swift Question

Trouble with switching views if users email and password are correct

Was wondering if anyone could help me out. I just finished my Sign Up page where the user can create an account. The problem I have now is that in the Login View the user can simply just press the Login button and it will redirect them to the next view even if their email and password are incorrect.

class LoginViewController: UIViewController, GIDSignInUIDelegate {
@IBOutlet var userEmailLoginField: UITextField!
@IBOutlet var userPasswordLoginField: UITextField!

@IBAction func loginButton(_: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = tabBarController

guard let email = userEmailLoginField.text, let password = userPasswordLoginField.text else { return }
FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
if let error = error {
print(error.localizedDescription)
return
}
}
}

Answer

Try moving your code that instantiates the new view controller. In the example below I moved it to only run if there is no error when authenticating with Firebase.

class LoginViewController: UIViewController, GIDSignInUIDelegate {
    @IBOutlet var userEmailLoginField: UITextField!
    @IBOutlet var userPasswordLoginField: UITextField!

    @IBAction func loginButton(_: Any) {

      guard let email = userEmailLoginField.text, let password = userPasswordLoginField.text else { return }
      FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
      if let error = error {
        print(error.localizedDescription)
        return
      } else {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabBarController = storyboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = tabBarController
     }
    }
   }
Comments