How to convert NSHTTPURLResponse to String in Swift
Solution 1
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"]
Solution 2
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.
Solution 3
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()
}
Solution 4
You'll need the code below, because the response data from your data task is stored in data
. response
is the http response, with status codes etc, for more info about http response go here
var responseString: String = String(data: data, encoding: NSUTF8StringEncoding)
Solution 5
If you want to see the answer json as a string, in Swift 5
let httpResponse = response as? HTTPURLResponse
if let jsonResponse = String(data: data!, encoding: String.Encoding.utf8) {
print("JSON String: \(jsonResponse)")
}
Related videos on Youtube
Karl Ivar
Updated on May 23, 2020Comments
-
Karl Ivar about 4 years
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?
-
HAS over 9 yearsThe compiler error is confusing.
data
needs to be of typeNSData
but you are passing it anNSHTTPURLResponse
. The method that is called (and returns a string) isNSHTTPURLResponse
'sdescription
method. -
Martin R over 9 yearsYou probably want to convert
data
to a string, notresponse
. -
Daij-Djan over 9 yearsyes but that isnt the response but a description ;) not good
-
Karl Ivar over 9 yearsI want to use the JSESSIONID found in the response and parse it, then pass it to a new dataTaskWithRequest.
-
Daij-Djan over 9 yearsit is a header field then?
-
Karl Ivar over 9 yearsYes it is a header field.
headers { "Content-Length" = 4730; "Content-Type" = "text/html;charset=ISO-8859-1"; Date = "Sun, 25 Jan 2015 21:25:28 GMT"; Server = "Apache-Coyote/1.1"; "Set-Cookie" = "JSESSIONID=83A31742591DD2714A090FC53D55EEED; Path=/talkmore3/; Secure; HttpOnly"; }
-
-
Daij-Djan over 9 yearsas I said, the description is not necessarily the responseData
-
Karl Ivar over 9 yearsI'm actually not looking for the data, or responseData. I need to get the response 'description' as a String that I can parse.
-
Daij-Djan over 9 yearshe wants the sessionID .. dont get why he should call description or (even more unrelated) NSHTTPURLResponse.localizedStringForStatusCode
-
Karl Ivar over 9 yearsThe response-'description' contains http response headers which contain a JSESSIONID I have to parse. edit: If I could access the JSESSIONID directly, that would of course be the optimal solution.
-
Daij-Djan over 9 yearsthe description has almost NO use and especially not for parsing data from it
-
Daij-Djan over 9 years[response valueForHTTPHeader:] (or what it is called) -- this is simply BAD advice
-
Daij-Djan over 9 yearsnote: parsing a description is almost like screen-scraping
-
Daij-Djan over 9 yearssee
let httpResponse = response as NSHTTPURLResponse
=> you have to cast it -
HAS over 9 years@Daij-Djan I changed my answer to reflect the changes. The question did not say anything about a header field, just printing the response.
-
Daij-Djan over 9 yearsyes responseData -- which is also not the response description -- IMO description has NO use except maybe debugging
-
HAS over 9 years@Daij-Djan That's exactly what I wrote 12 minutes ago.
-
Karl Ivar over 9 yearsI never intended to grab the data from the body. I was only interested in the header field, which also was included in the response description. However I understand it would be cumbersome to parse the description instead of reading the header field. Marked as the most correct answer.
-
Daij-Djan over 9 yearswhatever - I still find it wrong to even write this because it was CLEARLY not the real issue :D (especially no 2) anyway, revoked the vote, ciao
-
uliwitness about 6 yearsApple gives no guarantees about the format of object descriptions (beyond NSString and NSNumber). They are only intended for debugging and subject to change. As such, you do not want to make your app rely on the format of an object's description.