How to properly dismiss modal viewcontroller with completion handler

10,157

Solution 1

Pretty easy, pass funcToCall() as a completion parameter (important note - I'm using curly braces here):

viewController.dismissViewControllerAnimated(true, completion: { 
    funcToCall()
})

A completion parameter documentation:

The block to execute after the view controller is dismissed. This block has no return value and takes no parameters. You may specify nil for this parameter.

Solution 2

Just remove the brackets and pass the function name as parameter like this:

viewController.dismissViewControllerAnimated(true, completion: funcToCall)

This works as long as your function funcToCall is of type ()->Void like

func funcToCall() {  
    // do something
}
Share:
10,157
i6x86
Author by

i6x86

aprendiendo a crear aplicaciones para iPhone.

Updated on June 04, 2022

Comments

  • i6x86
    i6x86 almost 2 years

    I have viewController1 and viewController2 which is modaly presented and I want to use the completion handler when I dismiss the 2nd, but I can't get the implementation. I thought that I have to write a function and just put it there like:

    viewController.dismissViewControllerAnimated(true, completion: funcToCall())
    

    but then I get this error:

    Cannot convert value of type '()' to expected argument type '(() -> Void)?'

    Anyone can explain me, how can I execute properly the completion handler, please?