user2179936
user2179936

Reputation: 455

How do I pop to RootViewController when an alert is dismissed?

@IBAction func addButton(sender: AnyObject) {

    let alert = UIAlertController(title: "New Exercise Added", message: "\(name)", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok!!", style: UIAlertActionStyle.Default, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil)

    self.navigationController?.popToRootViewControllerAnimated(true)
    self.dismissViewControllerAnimated(true, completion: {})
    }

Within the IB action function of a button I have an alert, followed by some code to change to a different ViewController.

The program crashes upon reaching these lines of code after the alert:

2016-01-04 17:48:27.147 FitnessApp[60584:4080964] popToViewController:transition: called on while an existing transition or presentation is occurring; the navigation stack will not be updated.

How do I run the code to change ViewController after the transition is done?

Upvotes: 3

Views: 6127

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Your biggest issue is that you don't do anything with the alert button's handler. Instead, you immediately try to do the pop and dismiss after presenting the alert.

Move the code to pop the controller into the Ok button's alert handler.

@IBAction func addButton(sender: AnyObject) {
    let alert = UIAlertController(title: "New Exercise Added", message: "\(name)", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok!!", style: UIAlertActionStyle.Default, handler: {
        self.navigationController?.popToRootViewControllerAnimated(true)
        // You only need the pop
        //self.dismissViewControllerAnimated(true, completion: {})
    }))

    self.presentViewController(alert, animated: true, completion: nil)
}

Note: I'm not fluent in Swift so the syntax could be off a little.

Upvotes: 8

Related Questions