使用include()时ios json无法正常工作

时间:2014-02-12 16:24:51

标签: php ios json

我有一个应用程序,它接收由我的jason.php脚本生成的JSON文件,并在表视图中显示数据。

它工作正常,直到我尝试在我的jason.php文件中使用'include(db_connect.php)'将详细数据库日志传递给它。

运行我的php脚本,使用'include(db_connect.php)', 在浏览器中工作(返回正确格式化的JSON文件),但在我的手机上工作。

然而..

如果我只是将db_connect.php的内容粘贴到jason.php文件中,它在我的手机上工作...并且它在浏览器中返回完全相同的JSON文件。

两种方式都在浏览器中返回完全相同的JSON文本。

所有应用程序都希望从指定的URL接收JSON文件,它不会传递任何内容。只需访问URL并存储在NSData对象中返回的内容。

如果有人知道为什么会这样,我会很高兴知道!

由于

jason.php: 这会在浏览器中完美地返回JSON脚本

<?php

require("db_connect.php");


//Check to see if we can connect to the server
if(!$connection)
{
    die("Database server connection failed.");  
}
else
{
    //Attempt to select the database
    $dbconnect = mysql_select_db($db, $connection);

    //Check to see if we could select the database
    if(!$dbconnect)
    {
        die("Unable to connect to the specified database!");
    }
    else
    {
        $query = "SELECT * FROM cities";
        $resultset = mysql_query($query, $connection);

        $records = array();

        //Loop through all our records and add them to our array
        while($r = mysql_fetch_assoc($resultset))
        {
            $records[] = $r;        
        }

        //Output the data as JSON
        echo json_encode($records);
    }


}


?>

db_connect.php 登录详情

  <?php 
    $host = "xxxxx"; //Your database host server
    $db = "xxxxx"; //Your database name
    $user = "xxxxx"; //Your database user
    $pass = "xxxxx"; //Your password
    $connection = mysql_connect($host, $user, $pass);
 ?> 

jason_pasted.php 这与jason.php完全相同,但db_connect.php的内容只是粘贴在 - 在浏览器中产生完全相同的结果,并且在我的应用程序中使用时也有效

<?php

$host = "xxxxx"; //Your database host server
$db = "xxxxxx"; //Your database name
$user = "xxxxx"; //Your database user
$pass = "xxxxxx"; //Your password

$connection = mysql_connect($host, $user, $pass);


//Check to see if we can connect to the server
if(!$connection)
{
    die("Database server connection failed.");  
}
else
{
    //Attempt to select the database
    $dbconnect = mysql_select_db($db, $connection);

    //Check to see if we could select the database
    if(!$dbconnect)
    {
        die("Unable to connect to the specified database!");
    }
    else
    {
        $query = "SELECT * FROM cities";
        $resultset = mysql_query($query, $connection);

        $records = array();

        //Loop through all our records and add them to our array
        while($r = mysql_fetch_assoc($resultset))
        {
            $records[] = $r;        
        }

        //Output the data as JSON
        echo json_encode($records);
    }


}


?>

ViewController.m 摘自应用代码

    -(void) retrieveData
{
    NSURL *url = [NSURL URLWithString:jsonURL];
    NSData *data = [NSData dataWithContentsOfURL:url];
    json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    //set up cities array
    citiesArray = [[NSMutableArray alloc]init];

    for (int i=0;i<[json count]; i++)
    {
        //create city object
        NSString *cID = [[json objectAtIndex:i] objectForKey:@"id"];
        NSString *cName = [[json objectAtIndex:i] objectForKey:@"cityName"];
        NSString *cState = [[json objectAtIndex:i] objectForKey:@"cityState"];
        NSString *cPopulation = [[json objectAtIndex:i] objectForKey:@"cityPopulation"];
        NSString *cCountry = [[json objectAtIndex:i] objectForKey:@"country"];

        City *myCity = [[City alloc] initWithCityID:cID
                                        andCityName:cName
                                       andCityState:cState
                                  andCityPopulation:cPopulation
                                     andCityCountry:cCountry];

        //add city oject to city array
        [citiesArray addObject:myCity];

    }

    [davesTableView reloadData];


}

TL; DR应用程序与jason_pasted.php完美配合,但不是jason.php。 jason.php和jason_pasted.php在浏览器中打开时返回完全相同的JSON脚本。


从jason.php和jason_pasted.php返回的字符串

(
    {
    cityName = London;
    cityPopulation = 8173194;
    cityState = London;
    country = "United Kingdom";
    id = 1;
},
    {
    cityName = Bombay;
    cityPopulation = 12478447;
    cityState = Maharashtra;
    country = India;
    id = 2;
},
    {
    cityName = "Kuala Lumpur";
    cityPopulation = 1627172;
    cityState = "Federal Territory";
    country = Malaysia;
    id = 3;
},
    {
    cityName = "New York";
    cityPopulation = 8336697;
    cityState = "New York";
    country = "United States";
    id = 4;
},
    {
    cityName = Berlin;
    cityPopulation = 3538652;
    cityState = Berlin;
    country = Deutschland;
    id = 5;
}
)

仅当NSUrl指向jason.php

时才会返回

错误

    2014-02-13 11:43:34.760 JSONios[4655:60b] JSON error: Error Domain=NSCocoaErrorDomain Code=3840
 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or
 object and option to allow fragments not set.) 
UserInfo=0x14659c40 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

1 个答案:

答案 0 :(得分:0)

这是格式化的答案:

不要忽视错误!

不正确:

json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

注意:文档未指定可以为error参数传递nil。

正确:

// There is an assumption that the JSON head is a dictionary.
NSError *error;
NSDictionary *jsonAsDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (jsonAsDict == nil) {
    NSLog(@"JSON error: %@", error);
}
else { // For debug only
    NSLog(@"JSON: %@", jsonAsDict);
}

现在,这段代码会发生什么? 如果可能,请提供JSON字符串 哦,我个人不关心php如何创建JSON,我需要看到的只是JSON。

仍有问题:NSLog数据为字符串:

NSLog(@"data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

如果没有数据添加错误参数 dataWithContentsOfURL:options:error:
取代dataWithContentsOfURL: