Daniel Daniel - 1 year ago 93
Swift Question

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.

Rob Rob
Answer Source

I've done something like the following:

let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
    data, response, error in

    if let httpResponse = response as? NSHTTPURLResponse {
        if let contentType = httpResponse.allHeaderFields["Content-Type"] as? String {
            // use contentType here

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