How to get response headers when using Alamofire i

2020-02-28 03:59发布

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)"
        }  
    }
}

3条回答
男人必须洒脱
2楼-- · 2020-02-28 04:36

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

response.allHeaderFields
查看更多
迷人小祖宗
3楼-- · 2020-02-28 04:42

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"]
      // ...
   }
}
查看更多
时光不老,我们不散
4楼-- · 2020-02-28 04:52

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")
                        }
                    }
                }
}
查看更多
登录 后发表回答