TParizek
TParizek

Reputation: 580

Swift viewWillAppear delayed

past 5 hours I'm trying to fix this bug. I have two VC. There is a tap gesture that triggers segue in first VC.

@IBAction func addMaterial(sender: AnyObject){
        dispatch_async(dispatch_get_main_queue()) {
            self.performSegueWithIdentifier("addNewMaterialSegue", sender: self)
        }
    }

The second VC:

override func viewDidLoad() {
     dispatch_async(dispatch_get_main_queue()) {
        super.viewDidLoad()
        print("viewDidLoad")
    }
}


override func viewWillAppear(animated: Bool) {
    print("viewWillAppear")
    super.viewWillAppear(animated)
 }

It takes about 5 secounds from viewDidLoad to viewWillAppear. I know that I'm not the first to ask this question, but I didn't find different solution than "Creating and presenting the view controller should be done on the main thread" and thatś not my case.

Upvotes: 3

Views: 839

Answers (2)

Darko
Darko

Reputation: 9845

Remove dispatch_async everywhere in your sample code. You are already at the main queue.

EDIT:

Well, I have to apologize. I have tried your code but can't find any problems. At the first sight your dispatch_async calls which you are doing already on the main queue look really suspicious. And I still think they have to be removed. But they do not cause the problem you are experiencing. The view is opening really fast, without any delay, even if you put the calls in dispatch_async. So, there has to be another problem. Maybe you can give more information, more code, or best: the whole project. It should be easy to find the problems then.

If you can't give away the project you could do this check:

print("Current thread \(NSThread.currentThread())")

Place this on every entry of every involved function. Let's see in which contex currently everyting happens.

Upvotes: 4

Thomas Köhn
Thomas Köhn

Reputation: 123

Remove the dispatch_async's.

What you tell the processor with your dispatch_async is

  • as you said: yes, please run it on the main thread, because this is UI-related stuff. This is good.
  • the async says: dear processor, just keep going with what else is there that needs to be done – this could be a good thing as whatever calls your viewDidLoad has probably a lot of other stuff to do as well
  • unfortunately, however, in the whole view creation and display process, things depend on each other, understandably. if the view does not get loaded (via super.viewDidLoad()), then of course the VC can also not prepare the view to appear.
  • finally, dispatch_async can get several priorities. You will most likely not get the highest priority if you don't specify it explicitly. So a lot of other things will be prioritized over your calls by the processor.

Long story short, remove the dispatch_async, and your delay will be gone.

Upvotes: 6

Related Questions