我想在某个时间点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一时刻,暂停4秒,然后继续执行其余的代码。我该怎么做呢?
我正在使用Swift。
发布于 2014-12-17 10:59:58
发布于 2015-09-21 21:32:16
在大多数情况下,使用dispatch_after
块比使用sleep(time)
更好,因为在其上执行睡眠的线程被阻止执行其他工作。使用dispatch_after
时,正在处理的线程不会被阻塞,因此它可以在此期间执行其他工作。
如果你在你的应用程序的主线程上工作,使用sleep(time)
对你的应用程序的用户体验是不好的,因为在这段时间内UI没有响应。
Dispatch after调度代码块的执行,而不是冻结线程:
Swift≥3.0
let seconds = 4.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
// Put your code which should be executed with a delay here
}
异步环境中的Swift≥5.5:
func foo() async {
await Task.sleep(UInt64(seconds * Double(NSEC_PER_SEC)))
// Put your code which should be executed with a delay here
}
Swift < 3.0
let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue()) {
// Put your code which should be executed with a delay here
}
发布于 2016-10-25 08:47:45
你也可以用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")
}
https://stackoverflow.com/questions/27517632
复制相似问题