How to retrieve Alamofire response header for a request

前端 未结 1 1856
陌清茗
陌清茗 2020-12-16 11:28

how can I retrieve response headers for a request? Below is a request I make.

Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
           


        
相关标签:
1条回答
  • 2020-12-16 12:16

    If the response is type of NSHTTPURLResponse you can get header from response.allHeaderFields.

    So when you use Alamofire responseJSON you can access to NSHTTPURLResponse property like this :

    Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers).responseJSON {
            response in
            print(response.response?.allHeaderFields)
    }
    

    As apple documentation says :

    A dictionary containing all the HTTP header fields received as part of the server’s response. By examining this dictionary clients can see the “raw” header information returned by the HTTP server.

    The keys in this dictionary are the header field names, as received from the server. See RFC 2616 for a list of commonly used HTTP header fields.

    So to get for example a content-type in response header you can access it in that way :

    if let contentType = response.response?.allHeaderFields["Content-Type"] as? String {
            // use contentType here
    }
    
    0 讨论(0)
提交回复
热议问题