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

4

21

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.

Nothingness answered 1/9, 2014 at 19:25 Comment(0)
R
29

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.

Rhiannonrhianon answered 1/9, 2014 at 21:44 Comment(2)
Why do you need to cast it to NSString before casting it to String? Wouldn't as? String work?Reprint
That double casting was an early Swift 2 problem, which is now rendered unnecessary. But the use of value(forHTTPHeaderField:), shown in this revised answer, eliminates the String cast that allHeaderFields required, altogether.Rhiannonrhianon
N
2

This works with Xcode 6.1:

let contentType = httpUrlResponse?.allHeaderFields["Content-Type"] as String?

Multiple casts no longer required.

And in Xcode 6.3 with Swift 1.2, this works:

let contentType = httpUrlResponse?.allHeaderFields["Content-Type"] as? String
Nothingness answered 1/9, 2014 at 21:10 Comment(1)
The second statement works even pre-1.2, but I guess it didn't in September?Ballard
F
1

I use an extension to URLResponse to simplify this one (Swift 3):

extension URLResponse {

    func getHeaderField(key: String) -> String? {
       if let httpResponse = self as? HTTPURLResponse {
           if let field = httpResponse.allHeaderFields[key] as? String {
                return field
            }
        }
        return nil
    }
}
Financial answered 10/8, 2017 at 23:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.