how to stop a dispatchQueue in swift

后端 未结 3 1565
-上瘾入骨i
-上瘾入骨i 2021-01-13 17:43

I have a DispatchQueue for a introViewController that shows a gif for 11 seconds and then display my login page... But also have a button that skip the intro and display the

相关标签:
3条回答
  • 2021-01-13 17:52

    For this, you can use a DispatchWorkItem. Here is the reference:

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

    And here is an example of how you could use it in your code:

    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)    
        } 
    }
    
    0 讨论(0)
  • 2021-01-13 17:56

    I'm not sure if there are best practices here, but I would consider doing what you are doing with a Timer rather than the 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)
        }
    }
    
    0 讨论(0)
  • 2021-01-13 18:11

    You don't stop the queue. Instead, when the task that you dispatched starts executing, it needs to check its context and do the right thing (often: nothing) if the context has changed.

    0 讨论(0)
提交回复
热议问题