我已经浏览了Apple的iBook,但找不到任何定义:
有人可以解释dispatch_after
的结构吗?
dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)
答案 0 :(得分:1078)
我经常使用dispatch_after
我写了一个顶级实用程序函数来使语法更简单:
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
现在你可以这样说:
delay(0.4) {
// do stuff
}
哇,这是一种可以改善语言的语言。什么可能更好?
似乎几乎不值得打扰,因为他们已经改进了调用语法:
func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
答案 1 :(得分:711)
更清楚地了解结构:
dispatch_after(when: dispatch_time_t, queue: dispatch_queue_t, block: dispatch_block_t?)
dispatch_time_t
是UInt64
。 dispatch_queue_t
实际上是NSObject
的别名,但您应该使用熟悉的GCD方法来获取队列。该块是一个Swift闭包。具体而言,dispatch_block_t
定义为() -> Void
,相当于() -> ()
。
使用示例:
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
print("test")
}
修改强>
我建议使用@matt's really nice delay
function。
编辑2:
在Swift 3中,GCD会有新的包装器。见这里:https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md
原始示例将在Swift 3中编写如下:
let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
print("test")
}
请注意,您可以将deadlineTime
声明写为DispatchTime.now() + 1.0
并获得相同的结果,因为+
运算符被覆盖如下(类似于-
):
func +(time: DispatchTime, seconds: Double) -> DispatchTime
func +(time: DispatchWalltime, interval: DispatchTimeInterval) -> DispatchWalltime
这意味着如果您不使用DispatchTimeInterval
enum
并只写一个数字,则假定您正在使用秒。
答案 2 :(得分:103)
为了扩展Cezary的答案,该答案将在1纳秒后执行,我必须在4秒半后执行以下操作。
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)
编辑:我发现我的原始代码有些错误。如果不将NSEC_PER_SEC转换为Double,则隐式类型会导致编译错误。
如果有人能提出更优化的解决方案,我会热衷于听到它。
== Swift 3的更新==
这在Swift 3中非常简单和优雅:
DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
// ...
}
答案 3 :(得分:84)
matt's syntax非常好,如果您需要使块无效,您可能想要使用它:
typealias dispatch_cancelable_closure = (cancel : Bool) -> Void
func delay(time:NSTimeInterval, closure:()->Void) -> dispatch_cancelable_closure? {
func dispatch_later(clsr:()->Void) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(time * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), clsr)
}
var closure:dispatch_block_t? = closure
var cancelableClosure:dispatch_cancelable_closure?
let delayedClosure:dispatch_cancelable_closure = { cancel in
if closure != nil {
if (cancel == false) {
dispatch_async(dispatch_get_main_queue(), closure!);
}
}
closure = nil
cancelableClosure = nil
}
cancelableClosure = delayedClosure
dispatch_later {
if let delayedClosure = cancelableClosure {
delayedClosure(cancel: false)
}
}
return cancelableClosure;
}
func cancel_delay(closure:dispatch_cancelable_closure?) {
if closure != nil {
closure!(cancel: true)
}
}
使用方法如下
let retVal = delay(2.0) {
println("Later")
}
delay(1.0) {
cancel_delay(retVal)
}
上面的链接似乎已经失效。 Original Objc code from Github
答案 4 :(得分:22)
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#>
}
答案 5 :(得分:22)
Swift 3.0中最简单的解决方案Swift 4.0&amp; Swift 5.0
func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
用法
delayWithSeconds(1) {
//Do something
}
答案 6 :(得分:14)
另一种方法是像这样扩展Double:
extension Double {
var dispatchTime: dispatch_time_t {
get {
return dispatch_time(DISPATCH_TIME_NOW,Int64(self * Double(NSEC_PER_SEC)))
}
}
}
然后你可以像这样使用它:
dispatch_after(Double(2.0).dispatchTime, dispatch_get_main_queue(), { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})
我喜欢哑光的延迟功能,但仅仅是出于偏好,我宁愿限制传递闭合。
答案 7 :(得分:8)
在Swift 3.0中
派遣队列
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")
})
}
5秒后发货
DispatchQueue.main.after(when: DispatchTime.now() + 5) {
print("Dispatch after 5 sec")
}
答案 8 :(得分:4)
1)将此方法添加为UIViewController Extension的一部分。
extension UIViewController{
func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), block)
}
}
在VC上调用此方法:
self.runAfterDelay(5.0, block: {
//Add code to this block
print("run After Delay Success")
})
2)
performSelector("yourMethod Name", withObject: nil, afterDelay: 1)
3)
override func viewWillAppear(animated: Bool) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue(), { () -> () in
//Code Here
})
// Compact Form
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue()) {
//Code here
}
}
答案 9 :(得分:4)
Swift 3.0版本
关闭函数后,在主线程延迟后执行一些任务。
func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
onCompletion()
})
}
将此功能称为:
performAfterDelay(delay: 4.0) {
print("test")
}
答案 10 :(得分:3)
虽然不是OP的原始问题,但某些NSTimer
相关问题已被标记为此问题的重复,因此值得在此处添加NSTimer
答案。
NSTimer
vs dispatch_after
NSTimer
级别更高,dispatch_after
级别更低。NSTimer
更容易取消。取消dispatch_after
需要撰写more code。NSTimer
创建NSTimer
个实例。
var timer = NSTimer()
使用您需要的延迟启动计时器。
// 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."
}
timer.invalidate()
。repeats: true
。 如果您有一次性事件而无需取消,则无需创建timer
实例变量。以下就足够了:
NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
请参阅我的更全面的答案here。
答案 11 :(得分:2)
Swift 3&amp; 4:强>
您可以在DispatchQueue上创建扩展并添加在内部使用DispatchQueue asyncAfter函数的函数延迟
extension DispatchQueue {
static func delay(_ delay: DispatchTimeInterval, closure: @escaping () -> ()) {
let timeInterval = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: timeInterval, execute: closure)
}
}
使用:
DispatchQueue.delay(.seconds(1)) {
print("This is after delay")
}
答案 12 :(得分:2)
对于多种功能,请使用此功能。这对于将动画或Activity loader用于静态功能或任何UI更新非常有用。
DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) {
// Call your function 1
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// Call your function 2
}
}
例如-在重新加载tableView之前使用动画。或动画后的其他任何UI更新。
*// 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()
}
}
答案 13 :(得分:1)
在 Swift 4
中使用以下代码段:
let delayInSec = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + delayInSec) {
// code here
print("It works")
}
答案 14 :(得分:1)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: closure)
// example
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// just do it!
}
更简单。
答案 15 :(得分:1)
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
答案 16 :(得分:1)
在swift中使用asyncAfter延迟GCD调用
let delayQueue = DispatchQueue(label: "com.theappmaker.in", qos: .userInitiated)
let additionalTime: DispatchTimeInterval = .seconds(2)
我们可以延迟**微秒,毫秒,纳秒
delayQueue.asyncAfter(deadline: .now() + 0.60) {
print(Date())
}
delayQueue.asyncAfter(deadline: .now() + additionalTime) {
print(Date())
}
答案 17 :(得分:1)
这对我有用。
斯威夫特3:
let time1 = 8.23
let time2 = 3.42
// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
print("Sum of times: \(time1 + time2)")
}
目标-C:
CGFloat time1 = 3.49;
CGFloat time2 = 8.13;
// Delay 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CGFloat newTime = time1 + time2;
NSLog(@"New time: %f", newTime);
});
答案 18 :(得分:1)
我总是喜欢使用扩展而不是免费功能。
Swift 4
jhipster
使用如下。
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()
}
}
}
答案 19 :(得分:1)
延迟代码的另一个助手 100%Swift的使用,并且可选择选择其他线程来运行延迟代码:
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) {
// delayed code
}
如果您想将代码延迟到其他线程:
delay(bySeconds: 1.5, dispatchLevel: .background) {
// delayed code that will run on background thread
}
如果您更喜欢具有更强大功能的框架,请结帐 HandySwift 。您可以将它添加到您的项目 via Carthage ,然后使用它,就像上面的例子中一样,例如:
import HandySwift
delay(bySeconds: 1.5) {
// delayed code
}
答案 20 :(得分:0)
Swift 4有一个非常简短的方法:
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
// Your stuff here
print("hello")
}
答案 21 :(得分:0)
现在不仅仅是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")
}
答案 22 :(得分:0)
这是Swift中asyncAfter的同步版本:
let deadline = DispatchTime.now() + .seconds(3)
let semaphore = DispatchSemaphore.init(value: 0)
DispatchQueue.global().asyncAfter(deadline: deadline) {
dispatchPrecondition(condition: .onQueue(DispatchQueue.global()))
semaphore.signal()
}
semaphore.wait()
与异步代码一并使用:
let deadline = DispatchTime.now() + .seconds(3)
DispatchQueue.main.asyncAfter(deadline: deadline) {
dispatchPrecondition(condition: .onQueue(DispatchQueue.global()))
}
答案 23 :(得分:0)
使用此代码在2.0秒后执行一些与UI相关的任务。
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 3.0版本
关闭函数后,在主线程延迟后执行一些任务。
func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
onCompletion()
})
}
将此功能称为:
performAfterDelay(delay: 4.0) {
print("test")
}
答案 24 :(得分:0)
current queue
!除了这个问题的好答案之外,您还可以考虑保留当前队列以防止不必要的主队列操作(例如,当您尝试延迟某些异步操作时)。
func after(_ delay: TimeInterval,
perform block: @escaping ()->(),
on queue: DispatchQueue = OperationQueue.current?.underlyingQueue ?? .main) { // So this `queue` preserves the current queue and defaulted to the `main`. Also the caller can pass in the desired queue explicitly
queue.asyncAfter(deadline: .now() + delay, execute: block)
}
after(3) {
// will be executed on the caller's queue
print(Date())
}
答案 25 :(得分:-1)
要在延迟后执行功能或代码,请使用下一个方法
DispatchQueue.main.asyncAfter(deadline: .now() + 'secondsOfDelay') {
your code here...
}
示例-在此示例中,功能getShowMovies
将在1秒后执行
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.getShowMovies()
}