1
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!

1
  • I guess better way will be to use OperationQueue and Operation instead of GCD Commented Mar 4, 2020 at 14:15

1 Answer 1

1

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 {
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.