Delay Actions in Swift

user4001326 picture user4001326 · Nov 23, 2014 · Viewed 42.2k times · Source

I want to make an Activity Indicator start animating and then stop after one second.

So does anyone know how I could do that?

class stuff {
@IBOutlet weak var indicator: UIActivityIndicatorView!

   func iGotTriggeredBySomething {
      indicator.startAimating()
      //delay?
      indicator.stopAnimating()
   }
}

Thanks for answering.

Answer

Jeffery Thomas picture Jeffery Thomas · Nov 23, 2014

dispatch_after() is the standard way of delaying actions.

indicator.startAnimating()

let delay = 4.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
    indicator.stopAnimating()
}

See: dispatch_after - GCD in swift?


Update for Swift 3.0

indicator.startAnimating()

let delay = Int(4.5 * Double(1000))
DispatchQueue.main.after(when: .now() + .milliseconds(delay)) {
    indicator.stopAnimating()
}

However, in the spirit of Swift 3.0, I think extending DispatchQueue would be a better solution.

extension DispatchQueue {
    func delay(_ timeInterval: TimeInterval, execute work: () -> Void) {
        let milliseconds = Int(timeInterval * Double(1000))
        after(when: .now() + .milliseconds(milliseconds), execute: work)
    }
}

This leaves us with a very nice

indicator.startAnimating()

DispatchQueue.main.delay(4.5) {
    indicator.stopAnimating()
}

Update 2

Digging into the Xcode 8.0 beta, I found public func +(time: DispatchTime, seconds: Double) -> DispatchTime. So, I guess this is valid…

indicator.startAnimating()

DispatchQueue.main.after(when: .now() + 4.5) {
    indicator.stopAnimating()
}

I don't think there is a need to extend DispatchQueue for something this clean already.

--

Update for Swift 3.1

There is new syntax for Swift 3.1. They just likes to change things don't they.

indicator.startAnimating()

DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
    indicator.stopAnimating()
}