Answers:
结构的更清晰的想法:
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的非常好的delay
功能。
编辑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
而只写一个数字,则假定您使用的是秒。
dispatch_after(1, dispatch_get_main_queue()) { println("test") }
1
在dispatch_after(1, ...
这里使用数字可能会引起很多混乱。人们会认为它实际上是几秒,而实际上是纳秒。我建议参阅@brindy关于如何正确创建此数字的答案。
1
为,dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
因为它会导致混乱。人们可能会认为您不需要在Swift中创建dispatch_time_t
Binary operator '+' cannot be applied to operands of type DispatchTime and '_'
在线上let delayTime = DispatchTime.now() + .seconds(1.0)
DispatchTime.now() + 1.0
似乎是使其正常工作的唯一方法(无需这样做.seconds
)
我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)
}
func delayInSec(delay: Double) -> dispatch_time_t { return dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))) }
return
)。
1.0 ~~ { code...}
迅捷3+
在Swift 3+中,这非常简单,优雅:
DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
// ...
}
较旧的答案:
为了扩展将在1纳秒后执行的Cezary答案,我必须执行以下操作以在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,则隐式键入会导致编译错误。
如果有人可以提出更好的解决方案,我将很乐意听到。
dispatch_get_current_queue()
。我dispatch_get_main_queue()
改用了。
dispatch_get_main_queue()
绝对是您应该使用的。将更新。
matt的语法非常好,如果您需要使该块无效,则可以使用以下代码:
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)
}
上面的链接似乎已关闭。来自Github的原始Objc代码
performSelector:afterDelay:
Swift 2现在可用,因此您可以取消它。
dispatch_source_t
,因为可以取消它)来弥补其损失。
苹果拥有dispatch_after片段的Objective-C的:
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#>
}
另一种方法是像这样扩展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)
})
我喜欢马特的延迟功能,但出于偏爱,我宁愿限制传递闭包。
在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")
}
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")
}
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
})
//紧凑形式
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2), dispatch_get_main_queue()) {
//Code here
}
}
尽管不是OP最初提出的问题,但某些NSTimer
相关问题已标记为该问题的重复项,因此值得NSTimer
在此处提供答案。
NSTimer
与 dispatch_after
NSTimer
级别更高,而dispatch_after
级别更低。NSTimer
更容易取消。取消dispatch_after
需要编写更多代码。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)
在这里查看我的完整答案。
对于多种功能,请使用此功能。这对于将动画或活动加载器用于静态功能或任何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()
}
}
这对我有用。
斯威夫特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);
});
Swift 3和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")
}
另一个可以延迟使用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)
}
}
}
现在,您只需像下面这样在Main线程上延迟代码:
delay(bySeconds: 1.5) {
// delayed code
}
如果要延迟代码到另一个线程:
delay(bySeconds: 1.5, dispatchLevel: .background) {
// delayed code that will run on background thread
}
如果您希望框架也具有更多方便的功能,请签出HandySwift。您可以通过迦太基将其添加到您的项目中,然后像上面的示例一样使用它,例如:
import HandySwift
delay(bySeconds: 1.5) {
// delayed code
}
我总是喜欢使用扩展而不是免费功能。
斯威夫特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
}
迅速使用asyncAfter延迟GCD通话
let delayQueue = DispatchQueue(label: "com.theappmaker.in", qos: .userInitiated)
let additionalTime: DispatchTimeInterval = .seconds(2)
我们可以延迟为** microseconds,毫秒,纳秒
delayQueue.asyncAfter(deadline: .now() + 0.60) {
print(Date())
}
delayQueue.asyncAfter(deadline: .now() + additionalTime) {
print(Date())
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// ...
});
该dispatch_after(_:_:_:)
函数具有三个参数:
延迟
派遣队列
,阻塞或关闭
dispatch_after(_:_:_:)
在给定的延迟后,该函数将调用传递到该函数的调度队列上的块或闭包。请注意,延迟是使用dispatch_time(_:_:)
函数创建的。请记住这一点,因为我们也在Swift中使用了此功能。
在Swift 5中,在以下代码中使用:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure)
// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
Singleton.shared().printDate()
}
// default time gap is second, you can reduce it
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// just do it!
}
使用此代码在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")
}
现在,在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")
}
Swift 4的执行方法很短:
Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in
// Your stuff here
print("hello")
}
这是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()))
}