我正在使用Alamofire 4
从服务器下载文件,但有时服务器响应不包含标题文件名,我想处理此错误。 response.allHeaderFields["File-Name"] as! String
Error?
重写completion
如何捕获错误?
func download(id: Int, completion: @escaping (_ url: URL?, _ error: Error?) -> Void) {
print(id)
var filePath: URL?
var error: Error? = nil
let destination: DownloadRequest.DownloadFileDestination = { _, response in
let fileName = response.allHeaderFields["File-Name"] as! String
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let fileURL = documentsURL.appendingPathComponent(fileName)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download("\(serviceUrl)/\(language)/\(_controller)/DownloadFile", parameters: ["id": id], to: destination).responseData {
response in
switch response.result {
case .success(_):
filePath = response.destinationURL
break
case .failure(let errorData):
error = errorData
break
}
completion(filePath, error)
}
}
我正在使用: