我有表格视图,下载每个单元格的视频文件。这是我下载视频文件的代码。
func beginItemDownload(id:String,url:String,selectRow:Int) {
let pathComponent = "pack\(self.packID)-\(selectRow + 1).mp4"
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let directoryURL: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let folderPath: URL = directoryURL.appendingPathComponent("Downloads", isDirectory: true)
let fileURL: URL = folderPath.appendingPathComponent(pathComponent)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
let url = URL(string:url)
Alamofire.download(
url!,
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: nil,
to: destination).downloadProgress(closure: { (progress) in
DispatchQueue.main.async {
if progress.fractionCompleted < 1 {
print(Float(progress.fractionCompleted))
}
if progress.fractionCompleted == 1 {
print("Completed")
}
}
}).response(completionHandler: { (defaultDownloadResponse) in
if let destinationUrl = defaultDownloadResponse.destinationURL {
DispatchQueue.main.async {
print("destination url -****",destinationUrl.absoluteString)
}
}
if let error = defaultDownloadResponse.error {
debugPrint("Download Failed with error - \(error)")
return
}
})
}
当点击每个tableview单元格的下载按钮时,我可以下载视频文件并为每个单元格分配进度值。但是现在我想在每个单元格中点击取消按钮时取消对该单元格的下载请求,。我为这个问题搜索了不同的解决方案但我找不到任何解决方案来取消一个具有特定url字符串的请求。怎么能解决这个问题。谢谢你的回复。
未经测试但应该工作,使用originalRequest
(创建任务时的原始请求)或可选的currentRequest
(这是当前正在处理的请求)来查找要取消的特定任务:
func cancelSpecificTask(byUrl url:URL) {
Alamofire.SessionManager.default.session.getAllTasks{sessionTasks in
for task in sessionTasks {
if task.originalRequest?.url == url {
task.cancel()
}
}
}
}
或者只取消下载任务:
func cancelSepcificDownloadTask(byUrl url:URL) {
let sessionManager = Alamofire.SessionManager.default
sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
for task in downloadTasks {
if task.originalRequest?.url == url {
task.cancel()
}
}
}
虽然luiyezheng's answer真的很好并且应该完成这项工作,但开发人员有时会忽略它(例如我),Alamofire.download()
实际上会返回DownloadRequest
,如果需要可以存储在某处,以及后来的cancel()
:ed:
let request = Alamofire.download("http://test.com/file.png")
r.cancel()