Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 504
Daniel Avatar asked Sep 01 '14 19:09

Daniel


1 Answers

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.

like image 100
Rob Avatar answered Nov 04 '22 07:11

Rob