Anas Iqbal
Anas Iqbal

Reputation: 206

Unable to stop DispatchQueue.global().async task on swift

I am running a infinite loop to vibrate my phone inside dispatchQueue.global().async task so my UI doesn't get freeze, but the problem is I have been unable to stop it. below is my code

var queue: DispatchWorkItem?

queue = DispatchWorkItem {
            while (self.l > 1)
            {
                AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
            }
        }

        DispatchQueue.global().async(execute: queue!)

And below is the code where I am trying to stop it when the users leaves the screen

override func viewWillDisappear(_ animated: Bool) {
        queue?.cancel()
        l=0
        DispatchQueue.global().async {
            self.queue?.cancel()
        }
        print("view will disapear")
    }

Tried almost everything, but still failed to stop the global dispatch task. PS: I am new to iOS development :)

Upvotes: 0

Views: 2375

Answers (3)

Anas Iqbal
Anas Iqbal

Reputation: 206

Issue has been resolved, actually should't have used dispatch global async in first place. Tried doing it with a timer and it worked, vibrating after each secs and it doesn't freeze the UI, also gets stopped easily after just calling timer.invalidate(). Thanks for the help guys :)

Upvotes: 2

batphonghan
batphonghan

Reputation: 485

Actually var queue: DispatchWorkItem? is a DispatchWorkItem and can be canceled if not yet executed. So if you make sure DispatchQueue.global().async(execute: queue!) call after viewWillDisappear your code should work as expected.

Upvotes: 0

Mehul Thakkar
Mehul Thakkar

Reputation: 12594

GCD(Grand Central Dispatch) Queues cannot be stopped. If you want to stop the async queues then you have to use NSOperationQueue which has option to pause, resume, cancel the task in queue.

From your code, you can try one more thing to stop it, as you are using infinite loop to vibrate. Here in loop, you can add some condition to not vibrate further.

Upvotes: 1

Related Questions