26

how can I retrieve response headers for a request? Below is a request I make.

Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
        .responseJSON { response in switch response.result {
        case .Success(let JSON):

            ...

        case .Failure(let error):

            ...

    }

Thanks in advance!

qbo
  • 386
  • 1
  • 3
  • 8
  • This code gets response header in Swift 4.2 [https://stackoverflow.com/a/53501929/7707872](https://stackoverflow.com/a/53501929/7707872) – Abhay Korat Nov 28 '18 at 06:44

1 Answers1

59

If the response is type of NSHTTPURLResponse you can get header from response.allHeaderFields.

So when you use Alamofire responseJSON you can access to NSHTTPURLResponse property like this :

Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers).responseJSON {
        response in
        print(response.response?.allHeaderFields)
}

As apple documentation says :

A dictionary containing all the HTTP header fields received as part of the server’s response. By examining this dictionary clients can see the “raw” header information returned by the HTTP server.

The keys in this dictionary are the header field names, as received from the server. See RFC 2616 for a list of commonly used HTTP header fields.

So to get for example a content-type in response header you can access it in that way :

if let contentType = response.response?.allHeaderFields["Content-Type"] as? String {
        // use contentType here
}
Community
  • 1
  • 1
kamwysoc
  • 6,709
  • 2
  • 34
  • 48