在使用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!))")
}
我遗漏了什么?
发布于 2017-03-18 03:56:53
不确定您是否已经弄清楚了,但是您可以在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])
发布于 2020-04-14 18:24:06
下面是我使用的解决方案
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()
}
}
}
}
https://stackoverflow.com/questions/37327874
复制相似问题