【问题标题】:The method return the varible without modifying it该方法返回变量而不修改它
【发布时间】:2017-12-11 22:07:15
【问题描述】:

我的 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
}

【问题讨论】:

标签: ios swift firebase firebase-authentication


【解决方案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)
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多