matthewdossantos matthewdossantos - 4 months ago 20
Swift Question

Firebase login system

So here is the deal. Right now I have a viewcontroller where the user can signup, and it is working (checked in Firebase console). The next step is that I have another view with two fields and a Log in button. That login button now has a segue to the third view, home. But it is possible to click it even though nothing has been entered in the two textfields. The button should only work if the user enters his or he details he made in the signup view, thus logging in.

How can I do this?
already have the login code:

@IBAction func loginAction(sender: AnyObject)
{
if self.emailField.text == "" || self.passwordField.text == ""
{
let alertController = UIAlertController(title: "Oops!", message: "Please enter an email and password.", preferredStyle: .Alert)

let defaultAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alertController.addAction(defaultAction)

self.presentViewController(alertController, animated: true, completion: nil)
}
else
{
FIRAuth.auth()?.signInWithEmail(self.emailField.text!, password: self.passwordField.text!) { (user, error) in

if error == nil
{
self.emailField.text = ""
self.passwordField.text = ""
}
else
{
let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .Alert)

let defaultAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
alertController.addAction(defaultAction)

self.presentViewController(alertController, animated: true, completion: nil)
}


In the second if statement you see that it clears the fields to show the login worked.

What i need is that users can only login if the correct details are filled in, that are in the Firebase database.

Eli Eli
Answer

Instead of checking if there isnt any errors, check that there is data is the user object like this.

FIRAuth.auth()?.signInWithEmail(self.emailField.text!, password: self.passwordField.text!) { (user, error) in

        if user != nil
        {

        let VC = storyboard?.instantiateViewControllerWithIdentifier("Identifier") as! AccountViewController //The file that controls the view 

        self.presentViewController(VC, animated: true, completion: nil)

        }
        else
        {
            let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .Alert)

            let defaultAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
            alertController.addAction(defaultAction)

            self.presentViewController(alertController, animated: true, completion: nil)
        }
Comments