I'm trying to perform a segue after my IBAction has already happend. This is my code and as you can see when I press the button I make a get request with alamofire. The problem is that the request is (as I understand) an async method so the segue will unwind and perform eve if the getPlayer method hasn't done what it's supposed to. The only way I could fix it is by putting the perfomrsegue method inside an if statement where I check for the value of person.name, but I have to press the button twice and I just can't figure out how to solve this!
@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!)")
}
}
Perform segue after async alamofire request is completed.
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!)")
}
}
}