Objective-C PHP MySQL JSON - calling values


Objective-C PHP MySQL JSON - calling values

我这里有一个PHP脚本,它将数组转换为json:

while($row = $result->fetch_row()){
        $array[] = $row;
    }
   echo json_encode($array);

它返回这个

[["No","2013-06-08","13:07:00","Toronto","Boston","2013-07-07 17:57:44"]]

现在我尝试将这个json代码中的值显示到我的应用程序标签中。这是我的ViewController.m文件中的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *strURL = [NSString stringWithFormat:@"http://jamessuske.com/isthedomeopen/isthedomeopenGetData.php"];
    // to execute php code
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
    // to receive the returend value
    /*NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];*/

    self.YesOrNow.text = [NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];
}

但我的标签YesOrNow没有显示任何内容:(我做错了什么?

我需要安装JSON库吗?

您非常接近,但有几个问题:

  1. 您正在加载数据,但未成功导航结果。您返回的是一个带有一个项的数组,该项本身就是一个结果数组。yes/no文本值是该子数组的第一项。

  2. 您不应该在主线程上加载数据。将其分派到后台队列,在更新标签时,将其分派回主队列(因为所有UI更新都必须在主队列上进行)。

  3. 您应该检查错误代码。

因此,你可能会得到这样的结果:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadJSON];
}
- (void)loadJSON
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:@"http://jamessuske.com/isthedomeopen/isthedomeopenGetData.php"];
        NSError *error = nil;
        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
        if (error)
        {
            NSLog(@"%s: dataWithContentsOfURL error: %@", __FUNCTION__, error);
            return;
        }
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        if (error)
        {
            NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, error);
            return;
        }
        NSArray *firstItemArray = array[0];
        NSString *yesNoString = firstItemArray[0];
        NSString *dateString = firstItemArray[1];
        NSString *timeString = firstItemArray[2];
        // etc.
        dispatch_async(dispatch_get_main_queue(), ^{
            self.YesOrNow.text = yesNoString;
        });
    });
}