简体   繁体   中英

How to retrieve Alamofire response header for a request

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

Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
        .responseJSON { response in switch response.result {
        case .Success(let JSON):

            ...

        case .Failure(let error):

            ...

    }

Thanks in advance!

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM