SWIFT and PHP exchange with JSON

2020-07-24 04:48发布

问题:

iam using swift function to send POST query to php script

func post_retJSON_inJSON(params : Dictionary<String, String>,tourl:String)
    {
        let myUrl = NSURL(string: tourl);
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";

        var err: NSError?
        request.HTTPBody =  NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")


        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)")
            }

            UIApplication.sharedApplication().networkActivityIndicatorVisible = false

        }

        task.resume()
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }

With this php

$firstName= $_POST["firstName"];
$lastName = $_POST["lastName"]; 

$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);

// Send back request in JSON format
echo json_encode($returnValue);

AND then in swift i have a response

Optional({"firstName":null,"lastName":null})

I think i already try everything but I cant get in PHP parametres sended by SWIFT query. Help me please to figureout it!!!

回答1:

solved with this php and the same swift as in top

// Read request parameters
$postdata = json_decode(file_get_contents("php://input"),TRUE);

$firstName= $postdata["firstName"];
$lastName = $postdata["lastName"];
// Store values in an array
$returnValue = array("firstName"=>$firstName, "lastName"=>$lastName);

// Send back request in JSON format
echo json_encode($returnValue);