我第一次尝试使用服务器。
我已经下载了MAMP并在我的mac http://localhost:8888
上有一个本地服务器我有一个php文件jsontest.php,它显示了我从SQL数据库中获取的数据
<?php
// Database credentials
$host = 'localhost';
$db = 'json';
$uid = 'json';
$pwd = 'json1';
// Connect to the database server
$link = mysql_connect($host, $uid, $pwd) or die("Could not connect");
//select the json database
mysql_select_db($db) or die("Could not select database");
// Create an array to hold our results
$arr = array();
//Execute the query
$rs = mysql_query("SELECT id,userid,firstname,lastname,email FROM users");
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
?>
当我转到http://localhost:8888/jsontest.php(jsontest.php文件存储在MAMP / htdocs中)时,我可以看到我的数据:
{"users":[{"id":"1","userid":"fhardy","firstname":"Frank","lastname":"Hardy","email":"fhardy@hauntedclock.com"},{"id":"2","userid":"jhardy","firstname":"Joe","lastname":"Hardy","email":"jhardy@hauntedclock.com"},{"id":"3","userid":"ndrew","firstname":"Nancy","lastname":"Drew","email":"ndrew@hauntedclock.com"},{"id":"4","userid":"sdoo","firstname":"Scooby","lastname":"Doo","email":"sdoo@mysterymachine.com"}]}
然后我使用以下目标c代码从此服务器读取:
NSURL *url = [NSURL URLWithString:@"http://localhost:8888/jsontest.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; //
NSLog(@"jsonArray: %@", jsonArray);
但是应用程序因错误而崩溃
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
我知道错误来自我的服务器,因为它与教程中的服务器一起使用。但我不能让它与我的Mac上的本地服务器一起工作。我尝试过只使用http://localhost/jsontest.php,但它仍然无效。
非常感谢任何帮助。
答案 0 :(得分:2)