Fox Mulder Fox Mulder - 2 months ago 23
iOS Question

How to dismiss modal ViewController from UIAlertcontroller

I show a modal viewcontroller on which the user can decide to edit oder delete the presented car. If the user wants to delete this car I present an UIAlertController with alert style to ask if he really wants to delete this car. Everything works fine. But after the user chooses "Yes" I am still in the modal viewcontroller. How can I dismiss the modal view after the deletion?
I tried

self.parentViewController?.dismissViewControllerAnimated(true, completion: nil)

and
self.navigationController?.popViewControllerAnimated(true)
in the closure of the ok Action but both didn't worked for me. :(

Edit: The modal View is within an UINavigationController. This is my function to cal the UIAlertController.

func showDeleteWarningAndDeleteEntity() {
let deleteController = UIAlertController(title: "Delete car", message: "Are you sure?", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
(action) in
}
let okACtion = UIAlertAction(title: "Yes", style: .Destructive) {
(action) in
//some network stuff happens here...

self.dismissViewControllerAnimated(true, completion: nil)
}
deleteController.addAction(okACtion)
deleteController.addAction(cancelAction)
self.presentViewController(deleteController, animated: true, completion: nil)
}

Answer

Put your code inside the

 dispatch_async(dispatch_get_main_queue(), {    //write your code here

 })

like that :

func showDeleteWarningAndDeleteEntity() {

    dispatch_async(dispatch_get_main_queue(), {  

         let deleteController = UIAlertController(title: "Delete car", message: "Are you sure?", preferredStyle: .Alert)
    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
        (action) in
    }
    let okACtion = UIAlertAction(title: "Yes", style: .Destructive) {
        (action) in
        //some network stuff happens here...

        self.dismissViewControllerAnimated(true, completion: nil)
    }
    deleteController.addAction(okACtion)
    deleteController.addAction(cancelAction)
    self.presentViewController(deleteController, animated: true, completion: nil)
     })

}

Hope this will works for you

Comments