我想在某个点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一点上,暂停4秒,然后继续执行其余的代码。我该怎么做呢?
我用的是Swift。
我想在某个点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一点上,暂停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) { ... }
其他回答
如果你的代码已经在后台线程中运行,在Foundation: thread .sleep(forTimeInterval:)中使用这个方法暂停线程。
例如:
DispatchQueue.global(qos: .userInitiated).async {
// Code is running in a background thread already so it is safe to sleep
Thread.sleep(forTimeInterval: 4.0)
}
(当代码在主线程上运行时,请参阅其他答案以获得建议。)
要创建一个简单的时间延迟,您可以导入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秒打印。一切都如预期般顺利。
我认为最简单和最新的4秒计时器方法是:
Task {
// Do something
// Wait for 4 seconds
try await Task.sleep(nanoseconds: 4_000_000_000)
}
它使用了Swift 5.5的新并发。
在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。
Using a dispatch_after block is in most cases better than using sleep(time) as the thread on which the sleep is performed is blocked from doing other work. when using dispatch_after the thread which is worked on does not get blocked so it can do other work in the meantime. If you are working on the main thread of your application, using sleep(time) is bad for the user experience of your app as the UI is unresponsive during that time. Dispatch after schedules the execution of a block of code instead of freezing the thread:
斯威夫特≥ 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 {
try await Task.sleep(nanoseconds: 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
}