我翻遍了苹果的iBook,找不到任何关于它的定义:

有人能解释一下dispatch_after的结构吗?

dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)

当前回答

虽然不是OP的原始问题,但某些与NSTimer相关的问题已被标记为该问题的重复,因此值得在这里包含NSTimer的答案。

NSTimer vs dispatch_after

NSTimer更高级,而dispatch_after更低级。 NSTimer更容易取消。取消dispatch_after需要编写更多的代码。

用NSTimer延迟任务

创建一个NSTimer实例。

var timer = NSTimer()

以您需要的延迟启动计时器。

// invalidate the timer if there is any chance that it could have been called before
timer.invalidate()
// delay of 2 seconds
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) 

添加一个在延迟之后被调用的函数(使用您用于上面选择器参数的任何名称)。

func delayedAction() {
    print("Delayed action has now started."
}

笔记

如果需要在操作发生之前取消该操作,只需调用timer.invalidate()。 对于重复的动作使用repeats: true。 如果你有一个不需要取消的一次性事件,那么就不需要创建计时器实例变量。以下内容就足够了: NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) 在这里看到我更完整的回答。

其他回答

1)添加这个方法作为UIViewController Extension的一部分。

extension UIViewController{
func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue(), block)
    }
}

在VC上调用这个方法:

    self.runAfterDelay(5.0, block: {
     //Add code to this block
        print("run After Delay Success")
    })

2)

performSelector("yourMethod Name", withObject: nil, afterDelay: 1)

3)

override func viewWillAppear(animated: Bool) {

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue(), { () -> () in
    //Code Here
})

/ /紧凑的形式

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue()) {
    //Code here
 }
}

在Swift 5中,在下面使用:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }

Matt的语法非常好,如果你需要使块失效,你可能想使用这个:

typealias dispatch_cancelable_closure = (cancel : Bool) -> Void

func delay(time:NSTimeInterval, closure:()->Void) ->  dispatch_cancelable_closure? {

    func dispatch_later(clsr:()->Void) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(time * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), clsr)
    }

    var closure:dispatch_block_t? = closure
    var cancelableClosure:dispatch_cancelable_closure?

    let delayedClosure:dispatch_cancelable_closure = { cancel in
        if closure != nil {
            if (cancel == false) {
                dispatch_async(dispatch_get_main_queue(), closure!);
            }
        }
        closure = nil
        cancelableClosure = nil
    }

    cancelableClosure = delayedClosure

    dispatch_later {
        if let delayedClosure = cancelableClosure {
            delayedClosure(cancel: false)
        }
    }

    return cancelableClosure;
}

func cancel_delay(closure:dispatch_cancelable_closure?) {

    if closure != nil {
        closure!(cancel: true)
    }
}

使用方法如下

let retVal = delay(2.0) {
    println("Later")
}
delay(1.0) {
    cancel_delay(retVal)
}

学分

上面的链接似乎坏了。来自Github的原始Objc代码

Apple为Objective-C提供了dispatch_after代码段:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    <#code to be executed after a specified delay#>
});

以下是移植到Swift 3的相同代码片段:

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + <#delayInSeconds#>) {
  <#code to be executed after a specified delay#>
}

保留当前队列!

除了很好地回答这个问题之外,您还可以考虑保留当前队列以防止不必要的主队列操作(例如,当您试图延迟一些异步操作时)。

func after(_ delay: TimeInterval,
           perform block: @escaping ()->(),
           on queue: DispatchQueue = OperationQueue.current?.underlyingQueue ?? .main) { // So this `queue` preserves the current queue and defaulted to the `main`. Also the caller can pass in the desired queue explicitly
    queue.asyncAfter(deadline: .now() + delay, execute: block)
}

用法:

after(3) {
    // will be executed on the caller's queue
    print(Date())
}