停止dispatch_after

时间:2015-02-05 23:53:57

标签: swift animation dispatch

我使用动画来指定提示以帮助延迟交互使用这些:

 let delay = 1.8 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue()) {
        //call the method which have the steps after delay.

        self.rain.alpha = 0

        UIView.animateWithDuration(5, animations: {

            self.rain.alpha = 1

        })

        self.tip.startAnimating()

    }

但是,如果在动画开始之前,用户触摸屏幕,我需要停止此延迟过程。

5 个答案:

答案 0 :(得分:48)

iOS 8和OS X Yosemite推出dispatch_block_cancel,允许您在开始执行前取消它们

您在类中声明一个变量,如下所示:

var block: dispatch_block_t?

初始block变量,并在dispatch_after

中提供
block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
  print("I executed")
}
let time: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * NSEC_PER_SEC))
dispatch_after(time, dispatch_get_main_queue(), block!)

之后你可以按如下方式取消它:

dispatch_block_cancel(block!)

答案 1 :(得分:24)

Swift 3.0示例DispatchQueue取消或停止

var dispatchQueue: DispatchQueue?
var dispatchWorkItem: DispatchWorkItem?

func someOnClickButtonStart() {
    self.dispatchQueue = DispatchQueue.global(qos: .background) // create queue
    self.dispatchWorkItem = DispatchWorkItem { // create work item
        // async code goes here
    }
    if self.dispatchWorkItem != nil {
        self.dispatchQueue?.asyncAfter(
            deadline: .now() + .seconds(1),
            execute: self.dispatchWorkItem!
        ) // schedule work item
    }
}

func someOnClickButtonCancel() {
   if let dispatchWorkItem = self.dispatchWorkItem {
        dispatchWorkItem.cancel() // cancel work item
    }
}

答案 2 :(得分:8)

这是我在Swift中取消dispatch_after的一般解决方案:

typealias cancellable_closure = (() -> ())?

func dispatch_after(#seconds:Double, queue: dispatch_queue_t = dispatch_get_main_queue(), closure:()->()) -> cancellable_closure {
    var cancelled = false
    let cancel_closure: cancellable_closure = {
        cancelled = true
    }

    dispatch_after(
        dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue, {
            if !cancelled {
                closure()
            }
        }
    )

    return cancel_closure
}

func cancel_dispatch_after(cancel_closure: cancellable_closure) {
    cancel_closure?()
}

用法:

let doSomethingLater = dispatch_after(seconds: 3.0) {
    something()
}
....
if shouldCancelForSomeReason {
    cancel_dispatch_after(doSomethingLater)
}

默认情况下,它在主队列上运行,但您可以传入一个参数,使其在另一个队列上运行:

let doSomethingLater = dispatch_after(seconds: 3.0, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
    something()
}

答案 3 :(得分:3)

您可以创建一个布尔变量shouldCancelAnimation并在dispatch_after块内进行测试,以防止执行动画。

var shouldCancelAnimation = false // property of class

func runAnimation()
{
    let delay = 1.8 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue()) {

        if !self.shouldCancelAnimation
        {
            self.rain.alpha = 0
            UIView.animateWithDuration(5, animations: {
                self.rain.alpha = 1
            })

            self.tip.startAnimating()
        }
        self.shouldCancelAnimation = false
    }
}

func viewWasTouched() // This could be touches began or taprecognizer event
{
    shouldCancelAnimation = true
}

答案 4 :(得分:2)

在Swift 4.x中,只需共享即可:

var block: DispatchWorkItem?

self.block = DispatchWorkItem { self.go(self) }

// execute task in 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: self.block!)

,然后取消阻止,self.block?.cancel()

尝试这个示例项目:

import UIKit

class ViewController: UIViewController {

    var block: DispatchWorkItem?

    @IBAction func go(_ sender: Any) {
        self.block?.cancel()
        let vc2 = VC2()
        self.navigationController?.pushViewController(vc2, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .white
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        self.block = DispatchWorkItem { self.go(self) }

        // execute task in 2 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: self.block!)
    }    
}


class VC2: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .green
    }
}