NSTimer - how to delay in Swift NSTimer - how to delay in Swift ios ios

NSTimer - how to delay in Swift


Swift 3

With GCD:

let delayInSeconds = 4.0DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {    // here code perfomed with delay}

or with a timer:

func myPerformeCode() {   // here code to perform}let myTimer : Timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.myPerformeCode), userInfo: nil, repeats: false)

Swift 2

With GCD:

let seconds = 4.0let delay = seconds * Double(NSEC_PER_SEC)  // nanoseconds per secondslet dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))dispatch_after(dispatchTime, dispatch_get_main_queue(), {   // here code perfomed with delay})

or with a timer:

func myPerformeCode(timer : NSTimer) {   // here code to perform}let myTimer : NSTimer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("myPerformeCode:"), userInfo: nil, repeats: false)


With Swift 4.2

With Timer You can avoid using a selector, using a closure instead:

    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { (nil) in        // Your code here    }

Keep in mind that Timer is toll-free bridged with CFRunLoopTimer, and that run loops and GCD are two completely different approaches.... e


In swift we can delay by using Dispatch_after.

SWift 3.0 :-

DispatchQueue.main.asyncAfter(deadline: .now()+4.0) {        alert.dismiss(animated: true, completion: nil)    }


matomo