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
).
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
.