Search code examples
iosswiftxcodeseguedispatch-queue

cant manually control performSegue() inside dispatchqueue


I have a button object that runs a background thread for computation and a main thread for UI updates. After all is complete, I would like to move to another view controller using performSegue(withIdentifier: "thirdViewController", sender: self), but it does not work in the dispatchQueue. I have used performSegue() many times before to switch between view controllers and I could always manage to control it manually. Instead, it moves to the next ViewController almost instantly, without completing the computation first.

I tried using self.present(thirdViewController(), animated: true, completion: nil), and self.navigationController?.pushViewController(thirdViewController(), animated: true) to change the ViewController but they just gave me a black screen.

@IBAction func generateText(_ sender: Any) {
    DispatchQueue.global(qos: .userInteractive).async {
        //computation code
        DispatchQueue.main.sync {
            //update UI code
            self.performSegue(withIdentifier: "Segue2", sender: self)
        }
    }
}

Solution

  • This sort of behavior can be caused by a couple of different issues

    1. You might have both an @IBAction and segue attached to this button. Make sure you only have the @IBAction. The segue, itself, should not be attached to the button but rather should originate from the scene’s “view controller” outlet (in the top bar) rather than from the cell or button. If this is the case, remove the existing segue, and add another from the bar above the scene:

      enter image description here

      Then give that segue an identifier which you can then invoke programmatically.

    2. Alternatively the “computation code” is somehow allowing it to flow to the DispatchQueue.main.async call before completing (i.e. the computation code is initiating something that is, itself, asynchronous).

    Without seeing your code, we can’t say. But, it sounds like, from your subsequent comments, that the first observation was the source of the issue in your case, but I’ve outlined both options for the sake of future readers.