Ambroise Collon
Ambroise Collon

Reputation: 3869

Dismiss a View Controller with a UIAlertAction

I'm trying to present a log out alert. When the user taps on Yes, I want my view controller to dismiss with a method that can provide me a completion handler.

The view controller is inside a navigation controller and is the second one on the stack.

I came up with the following code:

@IBAction func logOut() {
        let logOutAlert = UIAlertController.init(title: "Log out", message: "Are you sure ?", preferredStyle:.Alert)

        logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
            //Present entry view ==> NOT EXECUTED
            self.dismissViewControllerAnimated(true, completion:nil)
        })

        logOutAlert.addAction(UIAlertAction.init(title: "Cancel", style: .Cancel, handler: nil))

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

The line self.dismissViewControllerAnimated(true, completion:nil) is read but it doesn't do anything.

Upvotes: 4

Views: 2391

Answers (1)

Gamma
Gamma

Reputation: 1367

I suspect that dismissViewControllerAnimated doesn't do anything for you because the view controller isn't presented modally, but shown by way of a navigation controller. To dismiss is, you can tell the navigation controller to pop it from the stack, like so:

    logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
        self.navigationController?.popViewControllerAnimated(true)
        })

Unfortunately, popViewControllerAnimated doesn't seem to provide a way to attach your own completion handler out of the box. If you require one, you could still add one by utilising the associated CATransaction, which could look something like this:

    logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
        CATransaction.begin()
        CATransaction.setCompletionBlock(/* YOUR BLOCK GOES HERE */)
        self.navigationController?.popViewControllerAnimated(true)
        CATransaction.commit()
        })

Upvotes: 5

Related Questions