How can I access the "Content-Type" header of an NSHTTPURLResponse?

Daniel picture Daniel · Sep 1, 2014 · Viewed 14.5k times · Source

Here's my naive first pass code:

var httpUrlResponse: NSHTTPURLResponse? // = (...get from server...)
let contentType = httpUrlResponse?.allHeaderFields["Content-Type"]

I've tried various derivations of this code, but I keep getting compiler warnings/errors related to the basic impedance mismatch between the NSDictionary type of the allHeaderFields property and my desire to just get a String or optional String.

Just not sure how to coerce the types.

Answer

Rob picture Rob · Sep 1, 2014

You can do something like the following in Swift 3:

let task = URLSession.shared.dataTask(with: url) { data, response, error in
    if let httpResponse = response as? HTTPURLResponse, let contentType = httpResponse.allHeaderFields["Content-Type"] as? String {
        // use contentType here
    }
}
task.resume()

Obviously, here I'm going from the URLResponse (the response variable) to the HTTPURLResponse, and getting the data from allHeaderFields. If you already have the HTTPURLResponse, then it's simpler, but hopefully this illustrates the idea.

For Swift 2, see previous revision of this answer.