In my iPhone application (develops in SWIFT) I\'ve got to communicate with a https service (with parameters) and needs to analyse the response.
All works ok but in s
@JibW this code will helps you to analyse response and easy to understand...do some additional changes as per your requirements.!
let URL = NSURL(string: "Paste your url here")!
var request = NSMutableURLRequest(URL: URL)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.timeInterval = 55.0
var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &error)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var data: NSData!
var response: NSURLResponse!
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var httpResponse = response as! NSHTTPURLResponse
println("\(httpResponse.statusCode)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else
{
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()