Get header data from a request response in swift
Update for iOS 13 and above.
I suggest if the response is of type HTTPURLResponse and you want get to a specific header value only. Then below is a better approach.
if let httpResponse = response as? HTTPURLResponse {
if let xDemAuth = httpResponse.value(forHTTPHeaderField: "X-Dem-Auth") as? String {
// use X-Dem-Auth here
}
}
If the response is type of NSHTTPURLResponse
you can get header from 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 X-Dem-Auth in response header you can access it in that way :
if let httpResponse = response as? NSHTTPURLResponse {
if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
// use X-Dem-Auth here
}
}
UPDATE
Updated due to comment from Evan R
if let httpResponse = response as? HTTPURLResponse {
if let xDemAuth = httpResponse.allHeaderFields["X-Dem-Auth"] as? String {
// use X-Dem-Auth here
}
}