该方法返回varible而不修改它

时间:2017-12-11 22:07:15

标签: ios swift firebase firebase-authentication

我的Swift代码有问题 当出现错误时,方法verifyInput应返回false 但它始终返回true,无论什么+当出现错误时它会打印“错误”,但它只是返回true

请帮助

@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
}

1 个答案:

答案 0 :(得分:1)

问题是verifyInput是从register同步调用的,但在其中是对具有完成块的Auth.auth().createUser的异步调用。

在异步调用完成之前返回check结果。您还需要将方法更改为异步。

你想要的东西模糊不清:

@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)
        }
    }
}