Home > Mobile >  How to get error message from response body when use Alamofire.download() request
How to get error message from response body when use Alamofire.download() request

Time:11-15

AF.download(url, parameters: params, to: destination)
  .validate(statusCode: [200])
  .response { response in
    switch response.result {
    case .success(let url):
      print("ok", url)
    case .failure(let err):
      print(err.localizedDescription)
    }
  }

When server response some error code like 4xx, 5xx, it will print "Response status code was unacceptable: xxx.", but I want the detail message in response body(server send plain text when error), I read some post that said we can retrieve response message with "response.data" but if use AF.download method, there isn't have "data" property with response object(Alamofire.AFDownloadResponse). so, is there any way to figure it out?

CodePudding user response:

This is from Alamofire Source Code;

The debug textual representation used when written to an output stream, which includes (if available) a summary of the URLRequest, the request's headers and body (if decodable as a String below 100KB); the HTTPURLResponse's status code, headers, and body; the duration of the network and serialization actions; and the Result of serialization.

Response debug description has status code information. So, the response should have status code information.

Also when I check source code, I see this part;

static func description(of response: HTTPURLResponse) -> String {
    """
    [Response]:
        [Status Code]: \(response.statusCode)
        \(DebugDescription.description(for: response.headers).indentingNewlines())
    """
}

So, response.status should give what your want. Good luck.

CodePudding user response:

Alamofire's DownloadResponse contains a fileURL: URL? property which can be used to load the downloaded data from disk even when validation or other actions produce a failure result in the response.

  • Related