我想在某个点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一点上,暂停4秒,然后继续执行其余的代码。我该怎么做呢?

我用的是Swift。


当前回答

使用DispatchQueue的. asyncafter方法,可以在给定时间后执行代码。例如,执行…在主线程中,1秒后看起来是这样的:

DispatchQueue.main.asyncAfter(deadline: .now() + 1) { ... }

使用我方便的延迟包装器结构,你可以以更奇特的方式执行它:

struct Delay {

    @discardableResult
    init(_ timeInterval: TimeInterval, queue: DispatchQueue = .main, executingBlock: @escaping () -> Void) {
        queue.asyncAfter(deadline: .now() + timeInterval, execute: executingBlock)
    }

}

用法:

Delay(0.4) { ... }

其他回答

在Swift 3.0中尝试以下实现

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

使用

delayWithSeconds(1) {
   //Do something
}

这是添加延迟的一种更简单的方式,不会影响线程执行。

let continueTime: Date = Calendar.current.date(byAdding: .second, value: 30, to: Date())!
while (Date() < continueTime) {
    //DO NOTHING
}

如果从UI线程调用,sleep会锁住你的程序,可以考虑使用NSTimer或分派计时器。

但是,如果你真的需要延迟当前线程:

do {
    sleep(4)
}

这使用了UNIX中的睡眠函数。

你也可以用Swift 3这样做。

像这样执行延迟后的功能。

override func viewDidLoad() {
    super.viewDidLoad()

    self.perform(#selector(ClassName.performAction), with: nil, afterDelay: 2.0)
}


     @objc func performAction() {
//This function will perform after 2 seconds
            print("Delayed")
        }
DispatchQueue.global(qos: .background).async {
    sleep(4)
    print("Active after 4 sec, and doesn't block main")
    DispatchQueue.main.async{
        //do stuff in the main thread here
    }
}