How to get response headers when using Alamofire in Swift?

前端 未结 3 1644
时光说笑
时光说笑 2021-01-02 00:47

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

相关标签:
3条回答
  • 2021-01-02 01:08

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

    response.allHeaderFields
    
    0 讨论(0)
  • 2021-01-02 01:14

    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"]
          // ...
       }
    }
    
    0 讨论(0)
  • 2021-01-02 01:20

    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")
                            }
                        }
                    }
    }
    
    0 讨论(0)
提交回复
热议问题