Whenever I send a HTTP request from my Swift app to my local server, it always responds with a 500 status, an empty Optional()
body, and a text/html Content-Type. I'm new to using HTTP in this way, so I am unsure where the error might be. I have installed pecl-http and (I think) I have it properly configured. I also (think) that I am setting the body and content type properly in the PHP code. I followed the Swift part of this tutorial for my Swift code and created the PHP myself; I just have no idea where the problem is. I think my error is in sending/receiving the response, so that's the code I have attached.
HTTP Response
Response: <NSHTTPURLResponse: 0x7f8b44828b80> { URL: http://localhost/practicejournal/includes/php/json_login.php } { status code: 500, headers {
Connection = close;
"Content-Length" = 0;
"Content-Type" = "text/html";
Date = "Sun, 21 Dec 2014 17:12:53 GMT";
Server = "Apache/2.4.9 (Unix) PHP/5.5.14";
"X-Powered-By" = "PHP/5.5.14";
} }
Body: Optional()
The operation couldn’t be completed. (Cocoa error 3840.)
Error could not parse JSON: 'Optional()'
Swift Code Receiving Response
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
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 {
if let parseJSON = json {
var success = parseJSON["success"] as? Int
println("Success \(success)")
} else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
}
}
})
PHP Code Sending Response
//If Login is successful
$conn = null;
$success = 1;
HttpResponse::status(200);
HttpResponse::setContentType("application/json");
HttpResponse::setData($success);
HttpResponse::send();
//If Login is unsuccessful
function loginError() {
$conn = null;
$sucsess = 0;
HttpResponse::status(200);
HttpResponse::setContentType("application/json");
HttpResponse::setData($success);
HttpResponse::send();
}