Search code examples
iosswiftuiactivityindicatorview

Showing activity indicator after a number of seconds?


I want to show an activity indicator for my network request if its taking a long time to complete.

Is there a way I can start the indicator after a certain number of seconds have passed to allow a request to complete? I dont want it to flash up instantly as that makes for a choppy UI/UX on fast requests, but cant see the best way to present it on longer requests?

I was considering using:

DispatchQueue.main.asyncAfter(deadline: .now() + 3.0, execute: {}

however this would cause the timer to display even if the request was completed within 3 seconds...


Solution

  • Use DispatchWorkItem:

    fileprivate var indicatorTask: DispatchWorkItem?
    

    to run it after those 3 seconds:

    func prepareActivityIndicator() {
        indicatorTask?.cancel()
        indicatorTask = DispatchWorkItem {
            // show indicator
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: indicatorTask!)
    }
    

    Since you have a reference to indicatorTask you can cancel it anytime.