danywarner danywarner - 6 months ago 30
iOS Question

performSegueWithIdentifier does not execute immediately

I have to validate something in order to decide whether I continue with the execution of the

viewDidload()
sentences or I perform a segue, but when I debug the code, the execution of the upcoming sentences after the performSegueWithIdentifier call continue and the user gets to see some of the UI of the current ViewController, I would like to make that validation within that ViewController instead of doing it within it's parent.

Here's some of my code:

override func viewDidLoad() {
super.viewDidLoad()
let questionD = self.question![DECRIPTION]
let type = self.question![TYPE] as? String;
if type == "60" {
performSegueWithIdentifier("showCameraSegue", sender: self)
}
setBackBtn()

self.lblResponse.text = questionD as? String;

lblResponse.backgroundColor = UIColor.whiteColor()
...
}

Answer

you could execute the lines of code after a delay of a maybe a half second, so that the new view controller will show before the code is executed.

You might wanna try implementing this somewhere..

func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
    dispatch_after(time, dispatch_get_main_queue(), block)
}

And then calling it like so:

runAfterDelay(delay: 0.5, {

    setBackBtn()

    self.lblResponse.text = questionD as? String;

    lblResponse.backgroundColor = UIColor.whiteColor()
    ...
})

This wouldn't run the segue immediately like you asked for... but it would make everything else run a little after your segue

Or maybe if you're using a navigation controller you can execute the code when you know the new view controller is presenting:

class MyViewControllerSubclass : UIViewController, UINavigationControllerDelegate {

func viewDidLoad() {
    self.navigationController.delegate = self
}

func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
    //put your code here
}
}