Vaidas
Vaidas

Reputation: 1337

Read JSON in PHP from Swift

I am having trouble with my php file reading JSON data. I use swift to send data to a server. I encode the request and when I send it as a string everything works fine. My String that works fine in PHP looks like this

id=e61db0&time=Feb 13, 2015 so this works fine when received by PHP

However, when I use dictionary and encode NSData my PHP file is not able to read it. I decoded the data that I send and it looks like that:

{"id":"e61db0", "time":"Feb 13, 2015"} this doesn't work when received by php

For my request setting headers I do this:

var imageData = UIImageJPEGRepresentation(ui_image, 0.5)
let base64encoded = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
var params = ["id": uid, "time": date, "comment": img_com_e, "image": base64encoded]
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"    
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var error: NSError?
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: .allZeros, error: &error)
        if let error = error {
            println("\(error.localizedDescription)")
        }
        let dataTask = session.dataTaskWithRequest(request) { data, response, error -> Void in
            let res = response as NSHTTPURLResponse!;
            NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data: data, encoding:NSUTF8StringEncoding)!
            return_val = responseData
            NSLog("Response ==> %@", responseData);
        } else {
            return_val = "bad"
            //println(return_val)
        }

    }

    dataTask.resume()

Not sure what is going on. Does my server PHP file does not recognize that it is JSON data and can't accept $_POST['id']. Should I set my headers somehow differently?

Upvotes: 0

Views: 991

Answers (1)

Alex
Alex

Reputation: 17289

Where is your php code?

If you send Content-Type: application/json

You should read php://input not $_POST

try:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["id"];

Upvotes: 1

Related Questions