Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response headers when using Alamofire in Swift?

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)"
        }  
    }
}
like image 604
Oguz Ozkeroglu Avatar asked Jan 13 '15 13:01

Oguz Ozkeroglu


People also ask

How do I pass Alamofire header in Swift?

For headers that change from request to request, you can pass them directly to the request method. From the docs: Adding a custom HTTP header to a Request is supported directly in the global request method. This makes it easy to attach HTTP headers to a Request that can be constantly changing.

How do I parse JSON response from Alamofire API in Swift?

How do I parse JSON response from Alamofire API in Swift? To parse the response in Alamofire API request, we will use JSONDecoder, which is an object that decodes instances of a data type from JSON objects. The decode method of JSONDecoder is used to decode the JSON response.


2 Answers

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

response.allHeaderFields
like image 132
Antoine Avatar answered Sep 27 '22 21:09

Antoine


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"]
      // ...
   }
}
like image 20
checklist Avatar answered Sep 27 '22 19:09

checklist