I'm trying to send a http request with swift to an PHP server. I managed on sending data and also reading response of server. I just want my php server to do different action depending on request type that is present in the json request
Here is my method for sending request :
func sendHttpRequests(data : Dictionary<String, AnyObject>) //-> NSDictionary
{
let url = NSURL ( string : "http://aaa.bbb.ccc.ddd")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL : url)
let payload1 = "\"r\":\"login\""
request.HTTPMethod = "POST"
request.HTTPBody = payload1.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
if let httpResponse = response as? NSHTTPURLResponse {
let responseCode = httpResponse.statusCode
print("Request Status \(responseCode)")
}
do
{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
print("Json received \(json)")
if let currItem = json["myKey"] as? String
{
print(currItem)
}
}
catch
{
print("error: \(error)")
}
}
}
When I just send a response back with this php script i get response successfully :
<?php
$arr = array("myKey" => "myValue");
echo json_encode($arr);
?>
Instead when I try something like this :
<?php
$postVar = $_POST['r'];
if (!empty($postVar))
{
$arr = array("status" => "it's ok");
echo json_encode($arr);
}
else
{
$arr = array("status" => "something wrong");
echo json_encode($arr);
}
?>
I get this error :
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}