stringswiftxcode6nshttpurlresponse

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?


Solution

  • 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"]