codeExperiment
codeExperiment

Reputation: 15

Beginner question on DispatchQueue.main.async

In MainViewController, in viewDidLoad() I'm calling a function which in turn tests if Auth.auth().currentUser == nil; If the condition is met then the statement to execute presents another view controller.

In the if statement, why does the statement to execute need to be preceded by DispatchQueue.main.async (if I don't write DispatchQueue.main.async then the view controller doesn't present and it's just stuck on MainViewController).

Upvotes: 1

Views: 1273

Answers (2)

Vikram Parimi
Vikram Parimi

Reputation: 777

Dispatch.main.async is used for reason being that all the UI related have to be performed on the mainQueue. Since UIViewController presentation is a UI task, hence performed on mainQueue

Also, to answer why it's not presenting when Dispatch.main is not used is perhaps you are doing it on a thread which isn't main.

Upvotes: 0

dan
dan

Reputation: 9825

Because at the time viewDidLoad is called your view controller has not yet been added to the view hierarchy. A view controller that is not part of the view hierarchy can't present another view controller. You should get a log message in the console saying something similar to that when you try to present the other view controller without async dispatch.

Putting the call in the DispatchQueue.main.async causes the presentation to be delayed until the next runloop cycle which happens to be enough that your view controller has been added to the view hierarchy once it gets called.

A better solution would be to put your current user check in a more appropriate place, possibly viewDidAppear.

Upvotes: 3

Related Questions