ggworean ggworean - 4 months ago 19
Swift Question

How can I see the server response from an HTTP GET request in Swift?

I'm using a RESTless API to make database queries to check for things like unique usernames and emails. However I'm not sure how to get the server code from the response compared to getting the return dictionary. For some searches if there's no result found it returns 404 and a non empty dictionary. So I can't simply check if the return dict is empty.

do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
}
catch {
print("failure")
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTaskWithRequest(request) {
data, response, error in

// Check for error
if error != nil
{
print("error=\(error)")
return
}

// Print out response string
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")


// Convert server json response to NSDictionary
do {
if let convertedJsonIntoDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

// Print out dictionary
print(convertedJsonIntoDict)
convertedDict = convertedJsonIntoDict
}
}
catch let error as NSError {
print(error.localizedDescription)
}

}

task.resume()

return convertedDict ?? nil

dan dan
Answer

There is data about the response in the response object passed in to the completion handler. For HTTP/HTTPS requests it's an NSHTTPURLResponse which contains a statusCode property which you can access.

let task = session.dataTaskWithRequest(request) {
        data, response, error in

    if let httpResponse = response as? NSHTTPURLResponse {
        let statusCode = httpResponse.statusCode
        // do whatever with the status code
    }

    ...
}
Comments