【发布时间】:2015-05-14 08:24:12
【问题描述】:
我正在使用 Swift 开发一个 iOS 应用程序,它应该根据用户的位置从 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;
谢谢
【问题讨论】:
-
嗨 Andrei,最简单的方法是您必须在服务器中创建 index.php 文件,并在您的 swift 应用程序中指定 myServerName.com/index.php url,在 php 文件中获取请求,如
if (isset($_POST["your_key_here"])) {$json = json_decode($_POST["your_key_here"]);} -
你需要使用 Alamofire 和 SwiftyJSON。
-
我的 Swift 代码没有问题!!我有它的 PHP
-
@styopdev 感谢您的回复,但是如果 (isset($_POST["your_key_here"])) 中的“your_key_here”应该是什么?我不使用表格。