Display a Loading/Waiting Activity Indicator (iOS/Swift)

Loading screen for iOS in Swift

Oftentimes, you need to display an activity indicator to the user when fetching or loading data.

 

It’s best to keep this in one place for ease of use. Also, it’s best to make sure this is done on the main/UI thread.

 

Loading Screen in Swift

 

 

Here’s a way to do it in an extension that adds it to all of your UIViewControllers…

 

 

Notice that the displaySpinner call returns the created UIView containing the activity indicator. Also, notice that the UI updates are done on the main thread.

To create and display the spinner, do this in your view controller:

This stores the view that’s created.

 

To remove it, do this:

This makes sure it’s done on the main thread.

Here’s how it could be used…

 

Since extensions can’t have stored properties this is one way to provide this functionality with an extension. Another way would be to create a class with static methods and a static UIView property. That’s one way I’ve done it in the past, but I wanted to do it as an extension this time.

There’s a variety of ways to solve this issue and this is one too. 🙂 Feel free to share you’re way of doing it.