Search code examples
xcodeswiftpresentviewcontrollercompletionhandler

Swift show view controller from a completion handler


I have a view controller with a function "CV" in it which constructs the views content. the function CV has a completion handler which returns itselve as the variable V. What I would now want to do is when I create a new Instance of that view that is shows V like so :

func S0000 (VD0000: O0001) {
    (self.storyboard!.instantiateViewControllerWithIdentifier("V0005") as! V0005).Cv (VD0000){ (V) -> Void in
        NSOperationQueue.mainQueue().addOperationWithBlock {
            self.presentViewController(V, animated: true, completion: nil)
        }
    }
}

This returns the error that V == nil which I dont understand why. I found out that If I write it like this :

func S0000 (VD0000: O0001) {
    let V = self.storyboard!.instantiateViewControllerWithIdentifier("V0005") as! V0005
    self.showViewController(V, sender: self)
    V.Cv (VD0000){ (V) -> Void in
        NSOperationQueue.mainQueue().addOperationWithBlock {
        }
    }
}

than it works, but this defeats the purpose which is to onley present V when its constuction is completed.

How could I do this ?


Solution

  • In the first function, your instance of the view controller goes out of scope as soon as the function is finished so it is no longer there when the completion handler is called.

    [EDIT]

    You could have a variable named preraringViewController:UIViewController? in the class containing S000 and use it to keep a reference to your view controller while .cv is preparing it.

    var preraringViewController:UIViewController? = nil
    func S0000 (VD0000: O0001) 
    {
       preraringViewController = self.storyboard!.instantiateViewControllerWithIdentifier("V0005")
       (preraringViewController as! V0005).Cv (VD0000)
        { (V) -> Void in
           NSOperationQueue.mainQueue().addOperationWithBlock {
            self.presentViewController(V, animated: true, completion: nil)
           preraringViewController  = nil
        }
    }
    

    }