问题
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.
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!))")
}
What am I missing?
回答1:
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)
}
}
}
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])
来源:https://stackoverflow.com/questions/37327874/check-if-a-file-already-exists-before-downloading-it-with-alamofire-suggestedd