在Swift中使用Alamofire时如何获取响应头?

时间:2015-01-13 13:59:11

标签: ios iphone swift http-headers alamofire

我正在使用Alamofire作为我的Rest(POST)请求并无缝地获得JSON响应。但我只能访问响应机构。我想获得响应标头。使用Alamofire时难道不可能吗?

这是我的代码段:

@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 个答案:

答案 0 :(得分:26)

由于响应属于NSHTTPURLResponse类型,您应该能够获得如下所示的标题:

response.allHeaderFields

答案 1 :(得分:6)

以下是如何在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"]
      // ...
   }
}

答案 2 :(得分:0)

此代码在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")
                        }
                    }
                }
}