如何在使用 Alamofire 重新下载之前检查给定文件是否已下载?我正在使用 suggestedDownloadDestination
,因此 Alamofire 会自动选择文件名并将其保存在所选目录中,例如 .CachesDirectory
。问题是 suggestedDownloadDestination
给出的值属于 DownloadFileDestination
类型,只有通过请求的 响应调用他才会返回
,但通过这种方式,如果之前不执行请求,我永远无法知道文件路径。NSURL
这是我目前使用 Alamofire 下载文件的代码:
Alamofire.download(.GET, downloadLink, destination: destination).progress {
bytesRead, totalBytesRead, totalBytesExpectedToRead in
}.response {
request, response, data, error in
guard error == nil else {
return
}
// This will give me the file path but we're already in a Request!
print("\(destination(NSURL(string: "")!, response!))")
}
我错过了什么?
最佳答案
不确定您是否想通了,但是您可以在 Alamofire.DownloadRequest
上创建一个扩展,例如:
extension Alamofire.DownloadRequest {
open class func suggestedDownloadDestination(
for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask,
with options: DownloadOptions)
-> DownloadFileDestination
{
return { temporaryURL, response in
let destination = DownloadRequest.suggestedDownloadDestination(for: directory, in: domain)(temporaryURL, response)
return (destination.destinationURL, options)
}
}
}
现在您可以在选项参数中指定是否要覆盖该文件:
let destination = DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory,
in: .userDomainMask,
with: [DownloadRequest.DownloadOptions.removePreviousFile])
关于ios - 在使用 Alamofire + suggestedDownloadDestination 下载文件之前检查文件是否已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37327874/