我想在某个点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一点上,暂停4秒,然后继续执行其余的代码。我该怎么做呢?
我用的是Swift。
我想在某个点暂停我的应用程序。换句话说,我希望我的应用程序执行代码,但在某一点上,暂停4秒,然后继续执行其余的代码。我该怎么做呢?
我用的是Swift。
当前回答
在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。
其他回答
NSTimer
@nneonneo的回答建议使用NSTimer,但没有说明如何使用。这是基本语法:
let delay = 0.5 // time in seconds
NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(myFunctionName), userInfo: nil, repeats: false)
这里有一个非常简单的项目来展示如何使用它。当一个按钮被按下时,它会启动一个计时器,在延迟半秒后调用一个函数。
import UIKit
class ViewController: UIViewController {
var timer = NSTimer()
let delay = 0.5
// start timer when button is tapped
@IBAction func startTimerButtonTapped(sender: UIButton) {
// cancel the timer in case the button is tapped multiple times
timer.invalidate()
// start the timer
timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
}
// function to be called after the delay
func delayedAction() {
print("action has started")
}
}
使用dispatch_time(如Palle的回答)是另一个有效的选项。然而,这很难取消。使用NSTimer,在延迟事件发生之前取消它,你所需要做的就是调用
timer.invalidate()
不建议使用sleep,特别是在主线程上,因为它会停止线程上正在完成的所有工作。
在这里可以看到我更完整的答案。
我同意Palle的观点,在这里使用dispatch_after是一个很好的选择。但是您可能不喜欢GCD调用,因为编写它们非常烦人。相反,你可以添加这个方便的助手:
public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
let dispatchTime = DispatchTime.now() + seconds
dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}
public enum DispatchLevel {
case main, userInteractive, userInitiated, utility, background
var dispatchQueue: DispatchQueue {
switch self {
case .main: return DispatchQueue.main
case .userInteractive: return DispatchQueue.global(qos: .userInteractive)
case .userInitiated: return DispatchQueue.global(qos: .userInitiated)
case .utility: return DispatchQueue.global(qos: .utility)
case .background: return DispatchQueue.global(qos: .background)
}
}
}
现在你只需在后台线程上延迟你的代码,就像这样:
delay(bySeconds: 1.5, dispatchLevel: .background) {
// delayed code that will run on background thread
}
在主线程上延迟代码甚至更简单:
delay(bySeconds: 1.5) {
// delayed code, by default run in main thread
}
如果你喜欢一个框架,也有一些更方便的功能,然后签出handysswift。你可以通过SwiftPM将它添加到你的项目中,然后像上面的例子一样使用它:
import HandySwift
delay(by: .seconds(1.5)) {
// delayed code
}
如果你的代码已经在后台线程中运行,在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)
}
(当代码在主线程上运行时,请参阅其他答案以获得建议。)
这是添加延迟的一种更简单的方式,不会影响线程执行。
let continueTime: Date = Calendar.current.date(byAdding: .second, value: 30, to: Date())!
while (Date() < continueTime) {
//DO NOTHING
}
斯威夫特5 <
使用任务。Sleep不会阻塞当前任务以外的任何代码,而且非常简单。
//Delay task by 4 seconds:
Task {
try await Task.sleep(nanoseconds: 4000000000)
//Execute your code here
}