ios - Alamofire DownloadRequest 验证并从服务器获取响应数据

标签 ios swift alamofire

我有以下方法

fileprivate func performDownloadRequest(_ request: DownloadRequest) {
request
      .validate()
      .downloadProgress { (progress: Progress) in
        ...
      }
      .response { response in 
        ...

其中 response'(DefaultDownloadResponse) -> Void'

我怎样才能使它成为 '(DownloadResponse) -> Void' ?请注意 DefaultDownloadResponseDownloadResponse

我想要这个的原因是因为 DownloadResponse

/// The result of response serialization.
public let result: Result<Value>

我希望检索服务器发送的 JSON 数据,以便为用户显示自定义文本。 DefaultDownloadResponse 没有响应数据。

感谢任何见解。

最佳答案

最重要的是,如果您想要一个 Result 类型,您将不得不使用 responseJSON。但是您不能使用简单的 DownloadRequest 来做到这一点。这提供了一些可能的选择:

  1. 如果您真的想使用下载请求,您可以在创建 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 的文件。

  2. 恕我直言,下载任务的理论上优势是峰值内存使用率较低。但是,如果您只是转身将该文件的内容加载到某个 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/

相关文章:

objective-c - Println() 是否在实时应用程序中使用内存?

ios - viewmodifier : puzzled about how the application is different for . shadow() 和 .font 中的 Swift body 方法

ios - 上下文闭包类型 'Response<AnyObject, NSError> -> Void' 需要 1 个参数,但在闭包主体中使用了 4 个

swift - 使用 alamofire multipart 上传图像数组

由于核心数据迁移,iOS 应用程序在启动屏幕上崩溃

ios - 从 UINavigationController 向下动画化 UINavigationBar 的位置 - iOS

swift - 如何在 Xcode 中关闭颜色文字?

ios - 快速控制流程

ios - inputAccessoryView 卡在屏幕底部

带有查询参数的 Alamofire.upload