Abhi V Abhi V - 1 year ago 76
iOS Question

Stop tasks until AlertController action occurs Swift

I tried to execute a task from the

parameter of
so that it would execute the desired function only after the
closed. However, the function was called before the action was taken in the alert. How do I wait to execute the function until an action is taken?

let alert = UIAlertController(title: "Wild Card Played", message: "Choose your suit", preferredStyle : .alert);
for suit in suits {
alert.addAction(UIAlertAction(title: suit, style: .default, handler: crazyEightPlayed))
self.present(alert, animated: true, completion: cpuTurn) //Upon completion call the cpuTurn() function

Answer Source

The problem currently is that cpuTurn is being called when the alert is displayed to the user, not when the user pressed "Okay". As you can see in the documentation here the completion function in the self.present method is "[executed] after the presentation finishes. This block has no return value and takes no parameters. You may specify nil for this parameter." The alert appears for the user, and the first UIViewController says "I have completed presenting the alert" and then runs the cpuTurn function.

You'll want to put the code in the handler of a UIAlertAction, which you appear to already have. You should move the cpuTurn call to the crazyEightPlayed function (or at least call cpuTurn from crazyEightPlayed)