How to convert NSHTTPURLResponse to String in Swift

body

grab the data and make it utf string if you want. The response's description is not the response body

let responseData = String(data: data, encoding: NSUTF8StringEncoding)

header field

if you want a HEADER FIELD instead:

let httpResponse = response as NSHTTPURLResponse
let field = httpResponse.allHeaderFields["NAME_OF_FIELD"]

Updated Answer:

As is turns out you want to get a header field's content.

if let httpResponse = response as? NSHTTPURLResponse {
    if let sessionID = httpResponse.allHeaderFields["JSESSIONID"] as? String {
        // use sessionID
    }
}

When you print an object its description method gets called.

This is why when you println() it you get a textual representation.

There are two ways to accomplish what you want.

  1. The easy way

    let responseText = response.description
    

However, this is only good for debugging.

  1. The localized way

    let localizedResponse = NSHTTPURLResponse.localizedStringForStatusCode(response.statusCode)
    

Use the second approach whenever you need to display the error to the user.


For a newer version in swift

   let task = session.dataTask(with: url) {(data, response, error) in

        let httpResponse = response as! HTTPURLResponse

        let type = httpResponse.allHeaderFields["Content-Type"]
        print("Content-Type", type)

        let l = httpResponse.allHeaderFields["Content-Length"]
        print("Content-Length", l)

        if let response = response {   // Complete response
            print(response)
        }


            }catch {
                print(error)
            }
        }
        }.resume()

}