我一直关注这个tutorial。除了将名称插入数据库之外,我已经完成了所有工作。分数插入就好了。以下是我在xCode中的代码
-(void)postData:(NSString *)userName withScore:(NSNumber *)gamesWon
{
// build up the request that is to be sent to the server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://indie-world.com/iOS/index.php"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"postValues" forHTTPHeaderField:@"METHOD"];
NSLog(@"%@", @"Request set up");
//create data that will be sent in the psot
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:userName forKey:@"name"];
[dictionary setValue:gamesWon forKey:@"score"];
NSLog(@"%@", @"values set up");
// serialize the dictionary data as json
NSData *data = [[dictionary copy] JSONValue];
NSLog(@"%@", dictionary);
[request setHTTPBody:data];
[request addValue:[NSString stringWithFormat:@"%d", data.length] forHTTPHeaderField:@"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection)
{
NSLog(@"Connection Failed");
}
NSLog(@"%@", @"connection granted");
}
这是我在php页面上的代码
<?php
/*Simple Service
This is just a simple php script that will return values ,the
method is selected using the value of HTTP_METHOD
*/
$con=mysql_connect("localhost","iOSDevelopment","IosDevelopment");
// Check connection
if (!$con)
{
echo("Could not connect to web service.");
}
$db_selected = mysql_select_db("iosDevelopment");
if ($_SERVER['HTTP_METHOD'] === 'postValues'){
$body;
/*Sometimes the body data is attached in raw form and is not attached
to $_POST, this needs to be handled*/
if($_POST == null){
$handle = fopen('php://input', 'r');
$rawData = fgets($handle);
$body = json_decode($rawData);
}
else
{
if (isset($_POST["name"]) && isset($_POST["score"]))
{
$name = $_POST["name"];
$score = $_POST["score"];
// Check to see if the info is all here. return $body to iOS app.
$body = $_POST;
}
else
{
$data['error'] = 'No Post values';
echo json_encode($data);
}
}
// add to mysql
$sql = "INSERT INTO `iosdevelopment`.`rw_high_score` (`score`, `name`) VALUES ('$score', '$name')";
if (!mysql_query($sql, $con))
{
$data['error'] = 'Score was not added';
echo json_encode($data);
}
$data['scoreAdded'] = $body;
echo json_encode($data);
}
else
{
$data['error'] = 'The Service you asked for was not recognized';
echo json_encode($data);
}
?>
我错过了什么? echo返回名称和分数。我不确定我错过了什么。
答案 0 :(得分:0)
我认为错误在你的PHP脚本中检查了这部分
$data['scoreAdded'] = $body;
echo json_encode($data);
我认为应该是
$data['scoreAdded'] = $body;
echo json_encode($data['scoreAdded']);
我不知道你为什么这么做,希望这会有所帮助:)