【问题标题】:Alamofire DownloadRequest validate and get the response data from the serverAlamofire DownloadRequest 验证并从服务器获取响应数据
【发布时间】:2018-01-12 20:46:31
【问题描述】:

我有以下方法

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 没有响应数据。

感谢您的任何见解。

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    底线,如果你想要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 的下载任务,除非有某些原因需要它(例如后台会话),但这取决于你。

    【讨论】:

    • 谢谢罗布。我不会将文件的内容加载到 JSON 中,我只会在出现错误时捕获服务器的 JSON 响应,因此我可以向用户显示在服务器端构建的自定义错误消息。
    猜你喜欢
    • 2019-01-13
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多