如何在swift中停止dispatchQueue

时间:2017-12-29 00:44:49

标签: swift dispatch-queue

我有一个用于introViewController的DispatchQueue,它显示11秒的gif,然后显示我的登录页面......但是还有一个跳过介绍并显示登录的按钮。当我点击它时,仍在运行的时间以及当我在应用程序中导航时,会在时间结束时返回登录。

这是我的班级

class GifClass: UIViewController {

@IBOutlet weak var gifImage: UIImageView!
@IBOutlet weak var skipButton: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()

    gifImage.loadGif(name: "promed")

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(11)) {

        self.performSegue(withIdentifier: "introLogin", sender: self)
    }

}


@IBAction func skip(_ sender: Any) {


    performSegue(withIdentifier: "introLogin", sender: self)

}

}

如何点击按钮停止时间?

3 个答案:

答案 0 :(得分:9)

为此,您可以使用DispatchWorkItem。以下是参考资料:

https://developer.apple.com/documentation/dispatch/dispatchworkitem

这是一个如何在代码中使用它的示例:

class GifClass: UIViewController {

    @IBOutlet weak var gifImage: UIImageView!
    @IBOutlet weak var skipButton: UIButton!

    private var workItem: DispatchWorkItem? // Create a private DispatchWorkItem property

    override func viewDidLoad() {
        super.viewDidLoad()

        gifImage.loadGif(name: "promed")

        workItem = { // Set the work item with the block you want to execute
            self.performSegue(withIdentifier: "introLogin", sender: self)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(11), execute: workItem!)
    }

    @IBAction func skip(_ sender: Any) {
        workItem?.cancel() // Cancel the work item in the queue so it doesn't run
        performSegue(withIdentifier: "introLogin", sender: self)    
    } 
}

答案 1 :(得分:1)

我不确定这里是否有最佳做法,但我会考虑使用Timer而不是DispatchQueue来做你正在做的事情。

class GifClass: UIViewController {

    @IBOutlet weak var gifImage: UIImageView!
    @IBOutlet weak var skipButton: UIButton!

    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()

        gifImage.loadGif(name: "promed")

        timer = Timer.scheduledTimer(timeInterval: 11, target: self, selector: #selector(timerAction), userInfo: nil, repeats: false)
    }

    @objc func timerAction() {
        performSegue(withIdentifier: "introLogin", sender: self)
    }

    @IBAction func skip(_ sender: Any) {
        timer.invalidate()
        performSegue(withIdentifier: "introLogin", sender: self)
    }
}

答案 2 :(得分:0)

你不能阻止队列。相反,当您调度的任务开始执行时,它需要检查其上下文并在上下文发生更改时执行正确的操作(通常:不执行任何操作)。