结束异步进程的正确方法

Proper way to end an Async process

所以我有这个代码:

@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
}

这可以正常工作,但是如果当前正在下载的项目需要更长的时间然后用户点击 "End" 按钮,则 "progress dialog" 在当前项目完成之前不会被关闭。这使得 "End" 按钮在用户看来不起作用。

在Android中我们可以中断AsyncTask进程并结束它。在 Swift 中还有其他方法吗?就像当用户点击 "End" 时,进程应该立即停止并关闭 "progress dialog"。

GDC不容易取消。

使用 NSOperation 子类,然后您可以轻松快速地取消。