在使用Alamofire +建议的下载位置下载文件之前,检查文件是否已存在
在使用Alamofire重新下载给定文件之前,如何检查给定文件?我使用的是 suggestedDownloadDestination
,因此Alamofire将自动选择文件名并将其保存在所选目录中,例如 .CachesDirectory
。问题是 suggestedDownloadDestination
给出的值是 DownloadFileDestination
类型,该值将返回 NSURL
仅通过调用请求的响应
来给他打电话,但是以这种方式,我以前不执行请求就无法知道文件路径。
How can I check if a given file has been already downloaded before re-downloading it by using Alamofire? I'm using suggestedDownloadDestination
so Alamofire will automatically choose the name of the file and save it in the choosen directory, for example the .CachesDirectory
. The problem is that the value given by suggestedDownloadDestination
is of type DownloadFileDestination
which will return a NSURL
only by calling him with the request's response
, but in this way I could not ever know the file path without performing a request before.
这是我目前使用Alamofire下载文件的代码:
This is the code I currently use to download a file with 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
创建扩展名,例如:
Not sure if you figured this out yet, but you can create an extension over Alamofire.DownloadRequest
like:
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)
}
}
}
现在您可以指定如果要覆盖文件,请在options参数中输入:
Now you can specify in the options parameter if you want the file to be overwritten:
let destination = DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory,
in: .userDomainMask,
with: [DownloadRequest.DownloadOptions.removePreviousFile])