user3367853
user3367853

Reputation: 39

No post data returned by post request using NSURLSession

I am trying to learn sending HTTP requests to my PHP based service.

On click of a button my code is:

@IBAction func clickForRequest(sender: AnyObject) {

    let myUrl = NSURL(string: "http://localhost/app");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";

    // Compose a query string
    let postString = "firstName=James&lastName=Bond";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil
        {
            println("error=\(error)")
            return
        }

        // You can print out response object
        println("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)")

        //Let's convert response sent from a server side script to a NSDictionary object:

        var err: NSError?
        var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary

        if let parseJSON = myJSON {
            // Now we can access value of First Name by its key
            var firstNameValue = parseJSON["firstName"] as? String
            println("firstNameValue: \(firstNameValue)")
        }

    }

    task.resume()

}

My PHP code is :

<?php

echo "<pre>";
print_r($_POST);
echo "</pre>";

?>

But the ResponseString I am getting is just an empty array:

Array( )

Thanks.

Upvotes: 0

Views: 607

Answers (1)

I think that the problem is that your PHP snippet doesn't output valid JSON which is what you are trying to deserialise.

Try this

<?php
exit(json_encode($_POST));
?>

Upvotes: 1

Related Questions