Search code examples
iosswiftgrand-central-dispatchnsoperationqueuedispatch-queue

stop dispatchquene().async in loop globally using swift


override func viewDidLoad() {
  super.viewDidLoad()    
            worktask = DispatchWorkItem {
                   for i in 1…4 {
                         sleep(2)
                          DispatchQueue.main.async {
                                 // run code
                                 fucntionAlert()
                           }
                   }
             }
            DispatchQueue.global().async(execute: worktask)
    }
    func fucntionAlert(){   
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
                DispatchQueue.global().sync {
                            self.worktask.cancel()
                 }
            }
    }

    @IBAction func action(_sender: Any){
            DispatchQueue.global().sync {
                 self.worktask.cancel()
            }
    }

I’m trying to run dispatchqueue for 4 times, each one starts after 2 seconds. Like timer. I don’t want to use timer because i have timer already running in uiapplication.

Now I’m trying to stop the dispatchqueue when moving to next view controller or clicking ok button. It still running and never stops. Any solution?

i need to stop when moving to next view controller and starts again when return to myviewcontroller. thanks!


Solution

  • Try this code below.

        worktask = DispatchWorkItem { [weak self] in
            for i in 1...4 {
                sleep(2)
                if self?.worktask?.isCancelled ?? true {
                    break
                }
                DispatchQueue.main.async {
                }
            }
        }