13

I'm using Alamofire for my Rest (POST) request and getting JSON response seamlessly. But i can access only response body. I want to get response headers. Isn't it possible when using Alamofire?

Here is my code snippet:

@IBAction func loginButtonPressed(sender: UIButton) {
    let baseUrl = Globals.ApiConstants.baseUrl
    let endPoint = Globals.ApiConstants.EndPoints.authorize

    let parameters = [
        "apikey": "api_key_is_here",
        "apipass": "api_pass_is_here",
        "agent": "agent_is_here"
    ]

    Alamofire.request(.POST, baseUrl + endPoint, parameters: parameters).responseJSON {
        (request, response, data, error) in let json = JSON(data!)

        if let result = json["result"].bool {
            self.lblResult.text = "result: \(result)"
        }  
    }
}
Oguz Ozkeroglu
  • 3,025
  • 3
  • 38
  • 64
  • 2
    I have no experience with Alamofire, but isn't `response` in the completion closure a `NSHTTPURLResponse` which has a `allHeaderFields` property? – Martin R Jan 13 '15 at 14:53

3 Answers3

29

As response is of NSHTTPURLResponse type, you should be able to get the headers as followed:

response.allHeaderFields
Antoine
  • 23,526
  • 11
  • 88
  • 94
  • 1
    If response is of NSHTTPURLResponse type then you don't have to cast it anymore... – Martin R Jan 13 '15 at 15:14
  • 1
    Yes, you're right. As I'm using Moya, I needed the cast as it's returning response as NSURLResponse. Edited my answer! – Antoine Jan 13 '15 at 19:20
  • Great I was looking how to do it using Moya, just need to dig into your edit :) Thanks! – VivienG May 09 '16 at 21:32
9

Here is how to access the response headers in Swift 3:

Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
   .responseJSON { response in
   if let headers = response.response?.allHeaderFields as? [String: String]{
      let header = headers["token"]
      // ...
   }
}
checklist
  • 12,340
  • 15
  • 58
  • 102
2

This code gets response header in Swift 4.2

Alamofire.request(pageUrlStr, method: .post, parameters: Parameter, encoding: URLEncoding.httpBody, headers: nil).responseJSON
            { response in
                //to get JSON return value
                if let ALLheader = response.response?.allHeaderFields  {
                    if let header = ALLheader as? [String : Any] {
                        if let cookies = header["Set-Cookie"] as? String {
                            UserDefaults.standard.set(cookies, forKey: "Cookie")
                        }
                    }
                }
}