Search code examples
iosswiftcontent-typenshttpurlresponse

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


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.


Solution

  • You can do something like the following in Swift 3:

    if
        let httpResponse = response as? HTTPURLResponse, 
        let contentType = httpResponse.value(forHTTPHeaderField: "Content-Type") 
    {
        // use contentType here
    }
    task.resume()
    

    Obviously, here I'm going from the URLResponse (the response variable) to the HTTPURLResponse. And rather than fetching allHeaderFields, I’m using value(forHTTPHeaderField:) which is typed and uses case-insensitive keys.

    Hopefully this illustrates the idea.

    For Swift 2, see previous revision of this answer.