简体   繁体   English

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

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

I am developing an iOS app with Swift that should fetch some data from a MySQL database according to the user's location. 我正在使用Swift开发一个iOS应用,该应用应根据用户的位置从MySQL数据库中获取一些数据。 I don't know PHP and I couldn't find a resource where it explains how to receive data from an app. 我不知道PHP,也找不到资源来解释如何从应用程序接收数据。

I have this PHP code: 我有这个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);
?>

as you can see when it is called it gets all the data from a table and returns it as a JSON. 如您所见,它在被调用时会从表中获取所有数据,并将其作为JSON返回。 The next step that I want to do is to send my location from the Swift app with this code: 我要做的下一步是使用以下代码从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()
        }

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

and I don't know how to "get"(accept, what function to use) this JSON: 而且我不知道如何“获取”(接受,使用什么功能)这个JSON:

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

from the app in order to have something like this in PHP: 从应用程序中获取,以便在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;

Thank you 谢谢

The answer is actually incredibly stupid-easy: 答案实际上是非常愚蠢的:

firstly nothing worked before I commented these two lines: 首先,在我评论这两行之前,没有任何效果:

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

Then I used a string instead of a JSON to send the POST data(it surely works with a JSON also, but this is what works at this moment): 然后,我使用字符串而不是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);

and at the server side simply: 而在服务器端:

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

:| :|

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM