Search code examples
iosswiftswift4dispatch-queue

Proper way to end an Async process


So I have this code:

@IBAction func onStart(_ sender: Any) {
    DispatchQueue(label: "SyncQueue").async{
        for i in 0..<numberOfItemToDownload {
            // download data from the internet this may takes longer depends on the connection speed and data being download
            if isCancelled {
                DispatchQueue.main.async { // dismiss the progress ViewController (displayed modally) }
                break
            }
        }
    }
}

@IBAction func onEnd(_ sender: Any) {
        isCancelled = true
}

This works ok, but if the current item being download takes longer then the user taps the "End" button the "progress dialog" is not dismissed until the current item is done. This makes the "End" button not working in user's perspective.

In Android we can interrupt the AsyncTask process and end it. Is there another way to do it in Swift? like when the user taps the "End" the process should immediately stop and dismiss the "progress dialog".


Solution

  • GDC is not easily cancellable.

    Use an NSOperation subclass then you can cancel easily and quickly.