Animations and race conditions

·

1 min read

When you use the navigation controller to present a view with an animation, Swift doesn't mark that view as being presented until the animation is completed.

So this can introduce some race conditions.

Let's say you present a loading view with an animation that lasts 5 seconds. The loading view is meant to be over the top of an async API call. The async API dismisses that loading view when it successfully returns a result, or gets an error.

However, the API call returns BEFORE the animation is completed. So then the API call will execute loadingView.dismiss, however there is no loading view that exists yet (because it's still animating).

So that means nothing is dismissed, and then the API call finishes, then the loading view animation finishes, and there is nothing that will dismiss the loading view.

So you are stuck.

To fix this, there are many ways. One way is to not use animations. Another could be to not use the navigation controller to present.