I download the file with Alamofire:
public func downloadFile(request: BaseRequest, progressIndicator: UIProgressView?, completion: @escaping(NetworkResult<String, NSString>) -> Void) {
if let progressIndicator = progressIndicator {
progressIndicator.isHidden = false
progressIndicator.progress = 0
}
if let filename = request.parameters["filename"], let displayName = request.parameters["displayname"], let url = URL(string: filename.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) {
let destination: DownloadRequest.Destination = { _, _ in
var documentsURL: URL!
if request.parameters.keys.contains("destination") {
let dest = "file://\(request.parameters["destination"]!)"
documentsURL = URL(string: dest.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
} else {
documentsURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]
documentsURL.appendPathComponent(displayName)
documentsURL = URL(string: filename.replacingOccurrences(of: "file://", with: "").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
documentsURL = URL(string: filename.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
}
return (documentsURL, [.removePreviousFile])
}
AF.download(url, to: destination)
.downloadProgress(queue: .main, closure: { (progress) in
if let progressIndicator = progressIndicator {
DispatchQueue.main.async {
progressIndicator.progress = Float(progress.fractionCompleted)
}
}
})
.responseData {
response in
progressIndicator?.isHidden = true
switch response.result {
case .failure(let error):
completion(NetworkResult.failure(NSString(string: error.errorDescription!)))
case .success(_):
completion(NetworkResult.success(response.fileURL?.path ?? ""))
}
}
} else {
completion(NetworkResult.failure(NSString(string: "Impossible de récupérer le fichier, requête \(request)")))
}
}