繁体   English   中英

Objective-C PHP MySQL JSON-调用值

[英]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. 您正在加载数据,但未成功浏览结果。 您将返回一个包含一项的数组,该数组本身就是结果数组。 是/否文本值是该子数组的第一项。

  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;
        });
    });

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM