如果我创建一个NSURLSessionDownloadTask,然后在它完成之前取消它,完成块仍然会似乎被触发.
let downloadTask = session.downloadTaskWithURL(URL,completionHandler: { location,response,error in ... }
如何在此块内检查下载任务是否被取消,以便在没有一个时,不尝试对所得到的下载进行操作?
解决方法
对于下载任务,将使用nil值为该位置调用完成处理程序,并且NSError对象的代码值将为NSURLErrorCancelled.在Swift 3:
let task = session.downloadTask(with: url) { location,error in if let error = error as? NSError { if error.code == NSURLErrorCancelled { // canceled } else { // some other error } return } // proceed to move file at `location` to somewhere more permanent } task.resume()
或在Swift 2:
let task = session.downloadTaskWithURL(url) { location,error in if let error = error { if error.code == NSURLErrorCancelled { // canceled } else { // some other error } return } // proceed to move file at `location` to somewhere more permanent } task.resume()
同样对于数据任务,完成处理程序将使用错误/ NSError来指示是否被取消.在Swift 3:
let task = session.dataTask(with: url) { data,error in if let error = error as? NSError { if error.code == NSURLErrorCancelled { // canceled } else { // some other error } return } // proceed to move file at `location` to somewhere more permanent } task.resume()
或在Swift 2:
let task = session.dataTaskWithURL(url) { data,error in if let error = error { if error.code == NSURLErrorCancelled { // canceled } else { // some other error } return } // otherwise handler data here } task.resume()