I have a heavily FileManager function. It copy files from A to B. I want to create a button to cancel that action. So I wrote this:
@IBAction func onClickCancelBtn(_ sender: NSButton) {
print(oq.isSuspended)
oq.cancelAllOperations()
}
//MARK: - Sync Button
var oq = OperationQueue()
@IBAction func onClickSyncBtn(_ sender: NSButton) {
ProgressBar.doubleValue = 0
ProgressInfo.isHidden = false
CancelBtn.isHidden = false
oq.addOperation {
self.OneWayBackUp(thePlaylists: selected_playlists)
}
}
It seems to be not working as I expected. Am I doing it wrong?
Cancellation with operations and operation queues is not automatic. When you cancel an operation, it simply sets a flag indicating that is has been cancelled. It's up to the operation's custom code to check that flag and cease its own work.
In general, it's not really feasible to stop a thread (or stop the work that thread is doing) without the cooperation of the code running in that thread. It would leave program state in a broken configuration (e.g. mutexes permanently locked).
Unfortunately, FileManager
doesn't provide a way to cancel its operations. You'll have to use a lower-level API to enable cancellation. The copyfile()
function is probably best. The docs are no longer online nor in Xcode's documentation, but you can use the man copyfile
command to see them.