How to convert NSHTTPURLResponse to String in Swift
Asked Answered
P

6

27

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?

Proboscis answered 25/1, 2015 at 21:16 Comment(6)
The compiler error is confusing. data needs to be of type NSData but you are passing it an NSHTTPURLResponse. The method that is called (and returns a string) is NSHTTPURLResponse's description method.Diametrically
You probably want to convert data to a string, not response.Subtle
yes but that isnt the response but a description ;) not goodHenton
I want to use the JSESSIONID found in the response and parse it, then pass it to a new dataTaskWithRequest.Proboscis
it is a header field then?Henton
Yes 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"; }Proboscis
H
46

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"]
Henton answered 25/1, 2015 at 21:28 Comment(3)
note: parsing a description is almost like screen-scrapingHenton
see let httpResponse = response as NSHTTPURLResponse => you have to cast itHenton
I 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.Proboscis
D
6

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.

Diametrically answered 25/1, 2015 at 21:31 Comment(8)
he wants the sessionID .. dont get why he should call description or (even more unrelated) NSHTTPURLResponse.localizedStringForStatusCodeHenton
The 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.Proboscis
the description has almost NO use and especially not for parsing data from itHenton
[response valueForHTTPHeader:] (or what it is called) -- this is simply BAD adviceHenton
@Henton I changed my answer to reflect the changes. The question did not say anything about a header field, just printing the response.Diametrically
yes responseData -- which is also not the response description -- IMO description has NO use except maybe debuggingHenton
@Henton That's exactly what I wrote 12 minutes ago.Diametrically
whatever - 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, ciaoHenton
M
4

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()

}
Mauriac answered 11/7, 2018 at 22:40 Comment(0)
C
2

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)
Counterirritant answered 25/1, 2015 at 21:29 Comment(0)
A
2

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)")
}
Andromache answered 10/3, 2020 at 21:3 Comment(0)
P
-1

It was as simple as var responseText: String = response.description.

Proboscis answered 25/1, 2015 at 21:28 Comment(3)
as I said, the description is not necessarily the responseDataHenton
I'm actually not looking for the data, or responseData. I need to get the response 'description' as a String that I can parse.Proboscis
Apple 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.Phi

© 2022 - 2024 — McMap. All rights reserved.