dispatch_after - GCD in swift? Swift 3, Swift 4. - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

7 Aug 2017

dispatch_after - GCD in swift? Swift 3, Swift 4.


dispatch_after - GCD in swift? Swift 3, Swift 4.


Grand Central Dispatch :

It's used to distribute the computation across multiple cores dispatching any number of threads needed and it is optimized to work with devices with multi-core processors. Basically we use this in iOS for running background threads.

Swift 2 and Objective-C syntax : 

dispatch_after(dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block)

Method 1 :

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    print("Delayed by 4 Seconds")
}

Method 2 :

This is using closure, so we can easily reuse anywhere by simply as follow.

func delayAction(xSeconds:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(xSeconds * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}
Simple call above method as following.

delayAction(0.5) {
    // do stuff here
    print("Delayed by 0.5 Seconds")
}
How to write dispatch_after GCD in Swift 3?
dispatch_after or asyncAfter in Swift 4.

Swift 3 and Swift 4 :

DispatchQueue.main.asyncAfter

Suppose if you want to execute a method after x amount of time then we can use 'dispatch_after' methods.

Let take a example. I want to execute a code after 4 seconds.

Method 1 :

let xSeconds = 4.0
DispatchQueue.main.asyncAfter(deadline: .now() + xSeconds) {
    print("Delayed by 4 Seconds")
}

Method 2 :

Using closure

func delayAction(_ xSeconds:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + xSeconds
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
Simple call above method as following.

delayAction(0.5) {
    // do stuff here
    print("Delayed by 0.5 Seconds")
}

For any queries please feel free to comment.

No comments:

Post a Comment

Post Top Ad