dispatch_after - GCD in Swift?

前端 未结 25 2848
心在旅途
心在旅途 2020-11-21 06:07

I\'ve gone through the iBook from Apple, and couldn\'t find any definition of it:

Can someone explain the structure of dispatch_after?

d         


        
25条回答
  •  遥遥无期
    2020-11-21 06:40

    use this code to perform some UI related task after 2.0 seconds.

                let delay = 2.0
                let delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
                let mainQueue = dispatch_get_main_queue()
    
                dispatch_after(delayInNanoSeconds, mainQueue, {
    
                    print("Some UI related task after delay")
                })
    

    Swift 3.0 version

    Following closure function execute some task after delay on main thread.

    func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){
    
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
           onCompletion()
        })
    }
    

    Call this function like:

    performAfterDelay(delay: 4.0) {
      print("test")
    }
    

提交回复
热议问题