无法使用Objective-C和JSON从外部数据库返回信息

时间:2012-05-28 19:23:25

标签: php objective-c json

我有点问题。我正在尝试使用php和Json从外部数据库中检索信息。 如果我从localhost尝试,它可以工作,但如果我修改URL并放置外部URL,它什么都不返回。 简而言之,如果我在本地工作(xampp和phpmyadmin)工作,我从数据库返回人口,但如果我尝试从外部数据库执行它不起作用。 代码有问题吗? 如果我运行托管在外部服务器上的php脚本,它将返回数据。这是Objective-C代码的问题

//Método que devuelve las poblaciones

-(NSMutableArray * )obtenerPoblaciones
{
pobla = [[NSMutableArray alloc] init];  

URLpobalciones = @"http://deproba.netau.net/devolver_poblaciones.php";
NSURL *url = [NSURL URLWithString:URLpobalciones];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *items = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions     error:&error];


NSDictionary *item = [[NSDictionary alloc] init];
// This will print all the names of people in your JSON.
for (item in items)
{
    NSString *poblae =[NSString stringWithFormat:[item valueForKey:@"nombre"]];
    [pobla addObject:poblae];
}

return pobla;

}


MODIFICATION

再次问好!我修改了代码。我希望得到一些简单的东西,然后让它复杂化。 我修改了php脚本和objective-c代码

PHP文件

<?php
header('Content-type: application/json');
$miArray = array(utf8_encode("París")=>"Francia", "Madrid"=>utf8_encode("España"));
echo(json_encode($miArray));
?>

目标-C代码

//NSURL *url = [NSURL URLWithString:@"http://search.twitter.com/search.json?q=g8production"];
NSURL *url = [NSURL URLWithString:@"http://prueba.vacau.com/php/prueba.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:url];

if (jsonData != nil) {
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:jsonData options:    (NSJSONReadingMutableContainers) error:&error];
    if (error == nil) {
        NSLog(@"Poblacion %@",result);
    }else
    {
        NSLog(@"jsonData  is empty");
    }
}

如果我使用URL(http://search.twitter.com/search.json?q=g8production),它工作正常,但如果我使用我的PHP脚本不起作用。使if / else语句打印:jsonData为空 我希望你能帮助我。再次感谢!

2 个答案:

答案 0 :(得分:0)

目前我无法写评论,所以一定是答案。我同意。您的代码似乎没问题,问题必须与您的服务器脚本有关。

但就我所看到的情况而言:

pobla = [[NSMutableArray alloc] init]; 

我认为这必须是iVar。请改用访问器。不要直接使用iVar的名字。如果您没有在项目中启用ARC,则可能是在泄漏内存。在通过retain属性设置后使用autorelease。

然后我不明白你为什么要用这个:

NSDictionary *item = [[NSDictionary alloc] init];
// This will print all the names of people in your JSON.
for (item in items) {...}

如果您正在考虑快速枚举,可以写:

for (NSDictionary *item in items) {...}

您不需要显式分配您枚举的对象。它们已经存在于items数组中。

答案 1 :(得分:0)

有效!我发现错误,试图在jsonlint.com上验证JSON问题是免费托管。添加广告和JSON验证器告诉您JSON格式不正确。我测试了一个真正的主机,它的工作原理。控制台显示从PHP获得JSON的值感谢所有人!你很酷