I would like to convert my response from the NSHTTPURLResponse type to String:
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
println("Response: \(response)")
var responseText: String = String(data: response, encoding: NSUTF8StringEncoding)
})
The line below outputs the response message to the console.
println("Response: \(response)")
But this line renders me an error: Extra argument 'encoding' in Call.
var responseText: String = String(data: response, encoding: NSUTF8StringEncoding)
How can I successfully convert this "response" into a String?
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)
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.
The easy way
let responseText = response.description
However, this is only good for debugging.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With