我有以下方法
fileprivate func performDownloadRequest(_ request: DownloadRequest) {
request
.validate()
.downloadProgress { (progress: Progress) in
...
}
.response { response in
...
其中 response
是 '(DefaultDownloadResponse) -> Void'
。
我怎样才能使它成为 '(DownloadResponse) -> Void'
?请注意 DefaultDownloadResponse
与 DownloadResponse
。
我想要这个的原因是因为 DownloadResponse
有
/// The result of response serialization.
public let result: Result<Value>
我希望检索服务器发送的 JSON 数据,以便为用户显示自定义文本。 DefaultDownloadResponse
没有响应数据。
感谢任何见解。
最佳答案
最重要的是,如果您想要一个 Result
类型,您将不得不使用 responseJSON
。但是您不能使用简单的 DownloadRequest
来做到这一点。这提供了一些可能的选择:
如果您真的想使用下载请求,您可以在创建
DownloadRequest
时指定下载文件的目的地,使用to
参数,例如// you may have to create the directory if it hasn't been created yet try! FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: true) // then you can use it: let destination = DownloadRequest.suggestedDownloadDestination(for: .downloadsDirectory) let req = Alamofire.download("http://httpbin.org/get", to: destination) perform(download: req)
然后:
func perform(download request: DownloadRequest) { request .validate() .downloadProgress { progress in print(progress) } .responseJSON { response in switch response.result { case .success(let value): print(value) case .failure(let error): print(error) } } }
如果您这样做,您可能希望在完成后删除位于
response.destinationURL
的文件。恕我直言,下载任务的理论上优势是峰值内存使用率较低。但是,如果您只是转身将该文件的内容加载到某个 JSON 对象中,我认为这会削弱下载任务产生的任何优势。那么,问题是为什么不使用数据任务呢?你可以只做一个
DataRequest
:let req = Alamofire.request("http://httpbin.org/get") perform(get: req)
然后:
func perform(get request: DataRequest) { request .validate() .downloadProgress { progress in print(progress) } .responseJSON { response in switch response.result { case .success(let value): print(value) case .failure(let error): print(error) } } }
就我个人而言,我倾向于数据任务而不是 JSON 的下载任务,除非您出于某种原因需要它(例如后台 session ),但这取决于您。
关于ios - Alamofire DownloadRequest 验证并从服务器获取响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48233792/