-1

i have a problem with my code in Swift the method verifyInput should return false when there's an error but it always return true no matter what + when there's an error it print "error" but its just return true

please help

@IBAction func register(_ sender: UIButton) {

    let check = verifyInput(email :email.text! ,password: password.text!)
    if(check==true){

        self.performSegue(withIdentifier: "goToAmazon", sender: nil)

    } else if(check==false) {

        self.message.text = "Sorry! there's an error"
    }


}

func verifyInput(email: String, password: String) -> Bool {

    var check = true
    Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
        if error != nil {
            print("error")
            check = false
        } else if(error==nil){
            check = true
            print("registered!")
        }

    }

   return check
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Dipie
  • 29
  • 3

1 Answers1

1

The problem is that verifyInput is being called synchronously from register but within it is an asynchronous call to Auth.auth().createUser with a completion block.

The check result is being returned before the asynchronous call ever completes. You need to change your method to be asynchronous as well.

Something vaguely like this is what you want:

@IBAction func register(_ sender: UIButton) {
    if let email = email.text, let password = password.text {
        verifyInput(email: email, password: password) { (check) in

            DispatchQueue.main.async {
                // only run UI code on the main thread
                if(check){
                    self.performSegue(withIdentifier: "goToAmazon", sender: nil)
                } else {
                    self.message.text = "Sorry! there's an error"
                }
            }
        }
    }
}

func verifyInput(email: String, password: String, escaping completion:@escaping (Bool)->Void) {

    Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
        if error != nil {
            print("error")
            completion(false)
        } else if(error==nil){
            print("registered!")
            completion(true)
        }
    }
}
David S.
  • 6,567
  • 1
  • 25
  • 45