Background

So while working on my latest SwiftUI project I ran into another situation where I needed to implement an Activity Indicator. This would be so that the user would know that something was happening in the background, and that the app didn’t crash. Now I know there are CocoaPods available that provide a variety of options and customization options, but I wanted one that looked like the system default so I opted to use UIActivityIndicator. However there was one problem, UIActivityIndicator is a UIKit implementation, so I had to get it working in SwiftUI. So after searching a number of resources online I was able to figure out how to do just that.

I wanted the Activity Indicator code to exist in it’s own place, as opposed to attaching it to an existing file so I started by creating a new file ActivityIndicatorView.swift. Then inside this file I went to work implementing an ActivityIndicator struct. This struct needs to conform to UIViewRepresentable which the documentation defines simply as being a “view that represents a UIKitView”. The UIViewRepresentable protocol was provided as a means to make UIKit views available and usable in SwiftUI.

The Activity Indicator we are working on implementing.

Code

Contents of ActivityIndicatorView.swift

Now for the best part, to use the Activity Indicator we just created you need to wrap the view you want to show it over so this would look like this in a SwiftUI view.

Now you’ll notice on line 9 that the .constant has a placeholder labelled <BOOLEAN VALUE> . This is because the .constant accepts a true or false value to control whether the activity indicator is being displayed or not. Now you can control this functionality anyway you want. So you could set such a value to true when the activity starts and set it to false once the activity has completed.

If you’re ever interested in watching me fail over and over again I stream that over on Twitch for the enjoyment of others (sometimes I succeed, which is cool).

https://www.twitch.tv/nyxdev