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

我用的是Swift。


当前回答

你可以创建扩展来轻松使用延迟函数(语法:Swift 4.2+)

extension UIViewController {
    func delay(_ delay:Double, closure:@escaping ()->()) {
        DispatchQueue.main.asyncAfter(
            deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
    }
}

如何在UIViewController中使用

self.delay(0.1, closure: {
   //execute code
})

其他回答

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

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

要创建一个简单的时间延迟,您可以导入Darwin,然后使用sleep(秒)来执行延迟。不过,这只需要几秒钟的时间,所以为了更精确的测量,你可以导入Darwin并使用usleep(百万分之一秒)进行非常精确的测量。为了验证这一点,我写道:

import Darwin
print("This is one.")
sleep(1)
print("This is two.")
usleep(400000)
print("This is three.")

打印,然后等待1秒打印,然后等待0.4秒打印。一切都如预期般顺利。

在Swift 3.0中尝试以下实现

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

使用

delayWithSeconds(1) {
   //Do something
}

作为之前建议的选项的替代解决方案,您可以使用基于DispatchGroup类的延迟,它被设计为同步多个异步任务的执行:

print("Start")
print(Date())

let delay = DispatchTimeInterval.seconds(3)
let group = DispatchGroup()
group.enter()
_ = group.wait(timeout: .now() + delay)

print("Finish")
print(Date())

其中,enter()方法用于显式地指示组代码的执行已经开始,wait(timeout:)方法用于等待组任务完成。当然,在本例中,这种情况永远不会发生,为此指定了一个超时,它等于所需的延迟。

使用它作为现成的帮手非常方便:

public class DispatchWait {
    private init () { }
    
    public static func `for` (_ interval: DispatchTimeInterval) {
        let group = DispatchGroup()
        group.enter()
        _ = group.wait(timeout: .now().advanced(by: interval))
    }
}

使用DispatchWait的示例:

print("Start")
print(Date())

DispatchWait.for(.seconds(3))

print("Finish")
print(Date())

不幸的是,我不能说这个延迟的准确性是多少,以及wait(timeout:)方法允许在指定的延迟之后继续执行程序的概率是多少。

此外,此解决方案允许您延迟当前队列中的代码,而不必在单独的闭包中执行它。

在Swift 4.2和Xcode 10.1中

你总共有4种方法来延迟。在这些选项中,首选选项1是在一段时间后调用或执行函数。sleep()是使用最少的情况。

选项1。

DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    self.yourFuncHere()
}
//Your function here    
func yourFuncHere() {

}

第二个选项。

perform(#selector(yourFuncHere2), with: nil, afterDelay: 5.0)

//Your function here  
@objc func yourFuncHere2() {
    print("this is...")
}

选项3。

Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(yourFuncHere3), userInfo: nil, repeats: false)

//Your function here  
@objc func yourFuncHere3() {

}

选项4。

sleep(5)

如果你想在一段时间后调用一个函数来执行一些东西,不要使用sleep。