1

ここに、配列を json に変換するこの PHP スクリプトがあります。

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 ライブラリをインストールする必要がありますか?

4

1 に答える 1

2

あなたはかなり近いですが、いくつかの問題があります:

  1. データを読み込んでいますが、結果をうまくナビゲートしていません。それ自体が結果の配列である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;
        });
    });

}
于 2013-07-08T05:06:12.617 に答える