let delay = 2.0
let delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
let mainQueue = dispatch_get_main_queue()
dispatch_after(delayInNanoSeconds, mainQueue, {
print("Some UI related task after delay")
})
现在不仅仅是Swift中Grand Central Dispatch(GCD)中异步调度的语法糖 .
添加Podfile
pod 'AsyncSwift'
然后,你可以像这样使用它 .
let seconds = 3.0
Async.main(after: seconds) {
print("Is called after 3 seconds")
}.background(after: 6.0) {
print("At least 3.0 seconds after previous block, and 6.0 after Async code is called")
}
3
I always prefer to use extension instead of free functions.
斯威夫特4
public extension DispatchQueue {
private class func delay(delay: TimeInterval, closure: @escaping () -> Void) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
class func performAction(after seconds: TimeInterval, callBack: @escaping (() -> Void) ) {
DispatchQueue.delay(delay: seconds) {
callBack()
}
}
}
使用方法如下 .
DispatchQueue.performAction(after: 0.3) {
// Code Here
}
let delay = 4.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), block)
DispatchQueue.delay(.seconds(1)) {
print("This is after delay")
}
4
Apple有 Objective-C 的dispatch_after片段:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
<#code to be executed after a specified delay#>
});
这是移植到 Swift 3的相同片段:
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + <#delayInSeconds#>) {
<#code to be executed after a specified delay#>
}
func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
1066
Swift 4有一个非常简短的方法:
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
// Your stuff here
print("hello")
}
1
For multiple functions use this. This is very helpful to use animations or Activity loader for static functions or any UI Update.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
// Call your function 1
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// Call your function 2
}
}
For example - Use a animation before a tableView reloads. Or any other UI update after the animation.
*// Start your amination*
self.startAnimation()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
*// The animation will execute depending on the delay time*
self.stopAnimation()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
*// Now update your view*
self.fetchData()
self.updateUI()
}
}
// invalidate the timer if there is any chance that it could have been called before
timer.invalidate()
// delay of 2 seconds
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
添加要在延迟后调用的函数(使用您在上面的 selector 参数中使用的任何名称) .
func delayedAction() {
print("Delayed action has now started."
}
DispatchQueue(label: "test").async {
//long running Background Task
for obj in 0...1000 {
print("async \(obj)")
}
// UI update in main queue
DispatchQueue.main.async(execute: {
print("UI update on main queue")
})
}
DispatchQueue(label: "m").sync {
//long running Background Task
for obj in 0...1000 {
print("sync \(obj)")
}
// UI update in main queue
DispatchQueue.main.sync(execute: {
print("UI update on main queue")
})
}
Dispatch after 5 seconds
DispatchQueue.main.after(when: DispatchTime.now() + 5) {
print("Dispatch after 5 sec")
}
0
延迟代码的另一个帮助是 100% Swift in usage ,并且可选地允许 choosing a different thread 运行延迟代码:
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 your code on the Main thread 就像这样:
delay(bySeconds: 1.5) {
// delayed code
}
如果你想 delay your code to a different thread :
delay(bySeconds: 1.5, dispatchLevel: .background) {
// delayed code that will run on background thread
}
如果您更喜欢 Framework ,它还有一些更方便的功能,那么请查看 HandySwift . 你可以将它添加到你的项目 via Carthage 然后使用它完全像上面的例子,例如:
22 回答
使用此代码在2.0秒后执行一些UI相关任务 .
Swift 3.0 version
关闭函数后,在主线程延迟后执行一些任务 .
将此功能称为:
现在不仅仅是Swift中Grand Central Dispatch(GCD)中异步调度的语法糖 .
添加Podfile
然后,你可以像这样使用它 .
I always prefer to use extension instead of free functions.
斯威夫特4
使用方法如下 .
Simplest solution in Swift 3.0 & Swift 4.0
用法
更清楚的结构:
dispatch_time_t
是UInt64
.dispatch_queue_t
实际上是NSObject
的别名,但您应该使用熟悉的GCD方法来获取队列 . 该块是一个Swift闭包 . 具体来说,dispatch_block_t
定义为() -> Void
,相当于() -> ()
.用法示例:
EDIT:
我建议使用@matt's really nice delay function .
EDIT 2:
在Swift 3中,将有新的GCD包装器 . 看这里:https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md
原始示例将在Swift 3中编写如下:
请注意,您可以将
deadlineTime
声明写为DispatchTime.now() + 1.0
并获得相同的结果,因为+
运算符被覆盖如下(类似于-
):func +(time: DispatchTime, seconds: Double) -> DispatchTime
func +(time: DispatchWalltime, interval: DispatchTimeInterval) -> DispatchWalltime
这意味着如果您不使用
DispatchTimeInterval
enum
并只写一个数字,则假定您使用的是秒 .Delaying GCD call using asyncAfter in swift
**We can delay as microseconds , milliseconds , nanoseconds
为了扩展Cezary的答案,它将在1纳秒后执行,我必须在4秒半后执行以下操作 .
编辑:我发现我的原始代码有点错误 . 如果不将NSEC_PER_SEC转换为Double,则隐式类型会导致编译错误 .
如果有人能提出更优化的解决方案,我会热衷于听到它 .
== Update for Swift 3 ==
这在Swift 3中非常简单和优雅:
Swift 3 & 4:
你可以在DispatchQueue上创建一个扩展并添加函数延迟,它在内部使用DispatchQueue asyncAfter函数
使用:
Apple有 Objective-C 的dispatch_after片段:
这是移植到 Swift 3的相同片段:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(10 * NSEC_PER_SEC)),dispatch_get_main_queue(),^ {// ...});
dispatch_after(:: _ :)函数有三个参数:
延迟调度队列块或闭包dispatch_after(:: _ :)函数调用在给定延迟后传递给函数的调度队列上的块或闭包 . 请注意,延迟是使用dispatch_time(::)函数创建的 . 请记住这一点,因为我们也在Swift中使用此功能 .
我建议通过教程Raywenderlich Dispatch tutorial
1)将此方法添加为UIViewController Extension的一部分 .
在VC上调用此方法:
2)performSelector(“yourMethod Name”,withObject:nil,afterDelay:1)
3)
//紧凑形式
}
我经常使用
dispatch_after
,因此我编写了一个顶级实用程序函数来使语法更简单:现在你可以这样说:
哇,你可以改善语言的语言 . 还有什么比这更好的?
更新Swift 3,Xcode 8 Seed 6
似乎几乎不值得打扰,现在他们改进了调用语法:
Swift 4有一个非常简短的方法:
For multiple functions use this. This is very helpful to use animations or Activity loader for static functions or any UI Update.
For example - Use a animation before a tableView reloads. Or any other UI update after the animation.
尽管不是OP的原始问题,但某些相关问题已被标记为此问题的重复,因此值得在此处提及
NSTimer
答案 .NSTimer vs dispatch_after
NSTimer
更高级别,而dispatch_after
更低级别 .NSTimer
更容易取消 . 取消dispatch_after
需要编写more code .使用NSTimer延迟任务
创建
NSTimer
实例 .使用您需要的延迟启动计时器 .
添加要在延迟后调用的函数(使用您在上面的
selector
参数中使用的任何名称) .注意事项
如果您需要在操作发生之前取消操作,只需调用
timer.invalidate()
即可 .对于重复操作,请使用
repeats: true
.如果您有一次性事件而无需取消,则无需创建
timer
实例变量 . 以下就足够了:Swift 3.0 version
关闭函数后,在主线程延迟后执行一些任务 .
将此功能称为:
matt's syntax非常好,如果你需要使块无效,你可能想要使用它:
使用方法如下
credits
上面的链接似乎有所下降 . Original Objc code from Github
另一种方法是像这样扩展Double:
然后你可以像这样使用它:
我喜欢matt的延迟功能,但仅仅是出于偏好,我宁愿限制传递闭包 .
In Swift 3.0
Dispatch queues
Dispatch after 5 seconds
延迟代码的另一个帮助是 100% Swift in usage ,并且可选地允许 choosing a different thread 运行延迟代码:
现在你只需 delay your code on the Main thread 就像这样:
如果你想 delay your code to a different thread :
如果您更喜欢 Framework ,它还有一些更方便的功能,那么请查看 HandySwift . 你可以将它添加到你的项目 via Carthage 然后使用它完全像上面的例子,例如:
这对我有用 .
斯威夫特3:
Objective-C的:
在 Swift 4
使用此代码段: