在ibaction

时间:2018-03-05 00:55:32

标签: ios swift asynchronous segue ibaction

在我的IBAction已经发生之后,我试图执行一个segue。 这是我的代码,当你按下按钮时我可以看到我用alamofire提出请求。问题是请求是(据我所知)异步方法,因此如果getPlayer方法没有完成它应该做的事情,segue将展开并执行eve。我可以解决它的唯一方法是将perfomrsegue方法放在if语句中,我检查person.name的值,但我必须按两次按钮,我只是无法弄清楚如何解决这个问题!

@IBAction func getPlayerPressed(_ sender: UIButton) {

    userDefaults.set(tagTextField.text!, forKey: "userTag")
    let userTag = userDefaults.string(forKey: "userTag")
    getPlayerData(with: userTag!)
    performSegue(withIdentifier: "goToPlayerProfile", sender: self)
 }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destionationVC = segue.destination as! PlayerProfileViewController
    destionationVC.playerName = player.name
    print(destionationVC.playerName)
    print("prepared for segue")
}


func getPlayerData (with tag: String) {
    let finalURL = baseURL + tag
    Alamofire.request(finalURL, headers: headers).responseJSON { (response) in
        if response.result.isSuccess {
            print("Got player data!")
            let playerJSON = JSON(response.result.value!)
            self.player.name = playerJSON["name"].stringValue
            print(self.player.name)
        } else {
            print("Error: \(response.result.error!)")
        }
    }

1 个答案:

答案 0 :(得分:0)

异步alamofire请求完成后执行segue。

func getPlayerData (with tag: String) {
    let finalURL = baseURL + tag
    Alamofire.request(finalURL, headers: headers).responseJSON { (response) in
        if response.result.isSuccess {
            print("Got player data!")
            let playerJSON = JSON(response.result.value!)
            self.player.name = playerJSON["name"].stringValue
            print(self.player.name)
            DispatchQueue.main.async {
                self.performSegue(withIdentifier: "goToPlayerProfile", sender: self)
            }
        } else {
            print("Error: \(response.result.error!)")
        }
    }
}