I am doing a POST request using URLSession.shared.dataTask which returns data, response and error. I would think that Error would be the same as a failed request. However, I can get the request to return proper JSON and httpStatus.statusCode is still 500. Error is nil. Alternatively if the request fails, I can see the html via the data object. However, the statusCode is also returning 500
How can statusCode be 500? The error nil and the request still return JSON or in general the difference between Error and response.statusCode. Given that what is proper way to parse what the dataTask returns. (Someone I asked about this told me the server is not properly configured but I can't verify this and don't have control of it as it is a shared hosting service.)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response:
URLResponse?, error: Error?) in
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// open 3 //check for http errors
print(httpStatus)//prints 500
}
if let `error` = error {
print(error.localizedDescription)//NO error
return
}
if let `data` = data {
let dataText = String(data: data, encoding: .utf8)
print(dataText)//in event of failure prints out html
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let jsonResults = responseJSON as? [String: Any] {
//In the event of success, parse the JSON here as in
let responsestr = jsonResults["response"] as? [String: Any]
let message = responsestr!["message"] as? String
print(message)
}
task.resume()