PHP:如何从JSON(从Swift iOS应用程序发送)中获取变量并以JSON响应


PHP: how to get variables from a JSON(sent from a Swift iOS app) and respond with a JSON

我正在开发一个iOS应用程序,Swift应该根据用户的位置从MySQL数据库获取一些数据。我不知道PHP,我找不到一个资源,它解释了如何从一个应用程序接收数据。

我有这样的PHP代码:

<?php
// Create connection
$con=mysqli_connect("localhost","*******","*******","*******");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM *******";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();
    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }
    // Finally, encode the array to JSON and output the results
    echo "{ '"posts'": ";
    echo json_encode($resultArray);
    echo "}";
}
// Close connections
mysqli_close($con);
?>
当调用

时,您可以看到它从表中获取所有数据并将其作为JSON返回。下一步,我要做的是从Swift应用程序发送我的位置,代码如下:

@IBAction func submitAction(sender: AnyObject) {
            //declare parameter as a dictionary which contains string as key and value combination.
            var parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String>
            //create the url with NSURL 
            let url = NSURL(string: "http://myServerName.com/api") //change the url
            //create the session object 
            var session = NSURLSession.sharedSession()
            //now create the NSMutableRequest object using the url object
            let request = NSMutableURLRequest(URL: url!)
             request.HTTPMethod = "POST" //set http method as POST
            var err: NSError?
            request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            //create dataTask using the session object to send data to the server
            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
                // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
                if(err != nil) {
                    println(err!.localizedDescription)
                    let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                    println("Error could not parse JSON: ''(jsonStr)'")
                }
                else {
                    // The JSONObjectWithData constructor didn't return an error. But, we should still
                    // check and make sure that json has a value using optional binding.
                    if let parseJSON = json {
                        // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                        var success = parseJSON["success"] as? Int
                        println("Succes: '(success)")
                    }
                    else {
                        // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                        let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                        println("Error could not parse JSON: '(jsonStr)")
                    }
                }
            })
            task.resume()
        }

来自http://jamesonquave.com/blog/making-a-post-request-in-swift/

和我不知道如何"获取"(接受,使用什么函数)这个JSON:

{"items": [
            {
                "minLat": "43.000000",
                "maxLat": "44.000000",
                "minLon": "-79.000000",
                "maxLon": "-78.000000",
            }
          ]
    }

以便在PHP中有这样的内容:

$minLat = $json['minLat'];
$maxLat = $json['maxLat'];
$minLon = $json['minLon'];
$maxLon = $json['maxLon'];
$sql = "SELECT * FROM ******* WHERE latitude BETWEEN".$minLat." AND ".$maxLat." AND longitude BETWEEN ".$minLon." AND ".$maxLon;

谢谢

答案其实非常简单:

首先,在我注释这两行之前没有任何工作:

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

然后我使用字符串而不是JSON来发送POST数据(它肯定也与JSON一起工作,但这是目前的工作原理):

let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "minLat=43.0&maxLat=44.0&minLon=26.0&maxLon=27.0";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

和在服务器端简单地:

$minLat = $_REQUEST["minLat"];
$maxLat = $_REQUEST["maxLat"];
$minLon = $_REQUEST["minLat"];
$maxLon = $_REQUEST["maxLat"];

: |