如何在使用Alamofire重新下载之前检查某个文件是否已经下载?我正在使用suggestedDownloadDestination
,因此Alamofire会自动选择文件的名称并将其保存在选择的目录中,例如.CachesDirectory
。问题是suggestedDownloadDestination
给出的值是DownloadFileDestination
类型,只有通过请求NSURL
调用它才能返回response
,但这样我就不能在不执行请求之前就知道文件路径。
这是我目前使用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!))")
}
我错过了什么?
答案 0 :(得分:1)
不确定您是否已将此解决,但您可以在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)
}
}
}
现在,您可以在options参数中指定是否要覆盖文件:
let destination = DownloadRequest.suggestedDownloadDestination(for: .cachesDirectory,
in: .userDomainMask,
with: [DownloadRequest.DownloadOptions.removePreviousFile])
答案 1 :(得分:0)
这是我使用的解决方案
func downloadDocumentFile(filePath: String,onDownloadProgress: @escaping(_ progress: Double) -> Void,onError: @escaping(_ errorMessage: String) -> Void,onSuccess: @escaping(_ destinationUrl: URL) -> Void){
guard let url = URL(string: filePath) else {
onError("Couldn't create url from passed file path")
assertionFailure()
return
}
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory, in: .userDomainMask)
Alamofire.download(url, to: destination)
.downloadProgress { (progress) in
onDownloadProgress(progress.fractionCompleted)
}
.responseData(queue: .main) { (response) in
switch response.result {
case .success:
if let destinationUrl = response.destinationURL {
onSuccess(destinationUrl)
}else {
onError("Couldn't get destination url")
assertionFailure()
}
case .failure(let error):
// check if file exists before
if let destinationURL = response.destinationURL {
if FileManager.default.fileExists(atPath: destinationURL.path){
// File exists, so no need to override it. simply return the path.
onSuccess(destinationURL)
print()
}else {
onError(error.localizedDescription)
assertionFailure()
}
}else {
onError(error.localizedDescription)
assertionFailure()
}
}
}
}