John Ramos John Ramos - 3 months ago 242
iOS Question

How to program a delay in Swift 3

In earlier versions of Swift, one could create a delay with the following code:

let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
//put your code which should be executed with a delay here
}


But now, in Swift 3, XCode automatically changes 6 different things but then the following error appears: "Cannot convert
DispatchTime.now
to expected value
dispatch_time_t
aka
UInt64
."

How can one create a delay before running a sequence of code in Swift 3?

Answer

After a lot of research, I finally figured this one out.

let when = DispatchTime.now() + 2 // change 2 to desired second delay.
DispatchQueue.main.after(when: when) {
// run your code with delay
}

This creates the desired effect in Swift 3.

Inspired by part of this answer.

Update for newest iteration of Swift 3:

let when = DispatchTime.now() + seconds
DispatchQueue.main.asyncAfter(deadline: when){
   // Your code
}