Marcus Leon
Marcus Leon

Reputation: 56669

Swift: How to display Activity Indicator for minimum amount of time?

Our app is calling a refreshData() method which displays an UIActivityIndicatorView while the refresh is running. The issue is the refresh can sometimes be very quick which results in the indicator appearing to flicker when it appears and disappears in quick succession. How can we ensure that the indicator appears for a minimum amount of time?

In other words ensure the indicator displays for at least two seconds even if the refresh completes very quickly.

Upvotes: 1

Views: 7527

Answers (2)

Duncan C
Duncan C

Reputation: 131408

Add an instance variable to record the start time when you begin the long-running task, and compute the elapsed time once the task is complete. (Let's say you store the elapsed time in a Double called elapsed.)

Use a call to DispatchQueue.main.asyncAfter() to turn off the activity indicator, and pass it a deadline of .now() if the long-running task took at least 2 seconds, or .now() + 2.0 - elapsed if it was less than 2 seconds.

Something like this:

var delay = 0.0
if elapsed < 2.0 {
  delay = 2.0 - elapsed
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
  activityIndicator.stopAnimating()
  activityIndicator.hidden = true
}

EDIT:

Incorporating Downgoat's suggestion, we can make the code cleaner and easier to read:

let delay = max(0.0, 2.0 - elapsed)
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
  activityIndicator.stopAnimating()
  activityIndicator.hidden = true
}

Upvotes: 7

Nicolas Bodin
Nicolas Bodin

Reputation: 1591

Swift >= 3.1

let delay = 2 // seconds
self.activityIndicator.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(delay)) {
    self.activityIndicator.stopAnimating()
    self.activityIndicator.isHidden = true
}

Upvotes: 1

Related Questions