如何在 swift 中停止 dispatchQueue

how to stop a dispatchQueue in swift

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

这是我的 class

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)

}

}

单击按钮时如何停止时间?

你不要停止排队。相反,当您分派的任务开始执行时,它需要检查其上下文并在上下文发生变化时做正确的事情(通常:什么都不做)。

为此,您可以使用 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 = DispatchWorkItem { // 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)    
    } 
}

我不确定这里是否有最佳实践,但我会考虑使用 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)
    }
}