Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSHTTPURLResponse to String in Swift

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?

like image 321
Karl Ivar Avatar asked Jan 25 '15 21:01

Karl Ivar


3 Answers

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"]
like image 184
Daij-Djan Avatar answered Dec 05 '22 08:12

Daij-Djan


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.

like image 23
HAS Avatar answered Dec 05 '22 06:12

HAS


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

}
like image 28
user3826696 Avatar answered Dec 05 '22 06:12

user3826696