0

私はxCodeでアプリを作っています。.json ファイルから JSON データをロードするメソッドがあります。これは正常に機能し、viewcontroller は JSON オブジェクトを表示します (解析後)。コードは次のとおりです。

- (void) loadJsonData
{
//Create an URL
NSURL *url = [NSURL URLWithString:@"http://www....json"];

//Sometimes servers return a wrong header. Use this to add a new accepted type
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/x-javascript"]];

//Create a request object with the url
NSURLRequest *request = [NSURLRequest requestWithURL:url];

//Create the JSON operation. The ^ blocks are executed when loading is done.
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

    //Do something with the JSON data, like parsing
    [self parseJSONData:JSON];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    //Do something with the error
    NSLog(@"Error :%@",response);

}];

//Start the operation
[operation start];
}

しかし、今は既存の .php ファイルから JSON オブジェクトを使用したいと考えています。URLを「http://www .... .php」に変更します。エラーは発生しませんでしたが、JSON が読み込まれません。ビューコントローラーにデータが表示されません。コード内の多くの変更を試みましたが、何も機能しません。.json url の代わりに .php を使用する場合、誰かが loadJsonData の正確なコードを教えてくれますか?

前もって感謝します!

4

1 に答える 1

0

お役に立てば幸いです。


私は自分のプロジェクトで次の関数を使用しています。

最初に次のようにjson文字列を取得PHPします

-(NSString *)httpRequest:(NSURL *)url {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSString *userAgent = [NSString stringWithFormat:@"myProject-IOS"];
    [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

    [request setHTTPMethod:@"GET"];

    [request setTimeoutInterval:25];

    NSURLResponse *response;

    NSData *dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    NSString *stringReply = [[NSString alloc] initWithData:dataReply encoding:NSASCIIStringEncoding];

    return stringReply;
}

NSString *link = @"http://domain.com/mypage.php";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",link]];
NSString *response = [NSString stringWithString:[R httpRequest:url]];

次のように、 SBSON to NSDictionary を使用して JSON 文字列を解析した後

-(NSMutableDictionary *) parse:(NSString *)str {
    SBJSON *parser = [[SBJSON alloc] init];
    NSMutableDictionary *results = [parser objectWithString:str error:nil];
    //[parser release];

    return results;
}

NSDictionary *results = [R parse:response];

私のPHPページは次のようになります

<?php

$array = array();

$array1 = array("a"=>"A", "b"=>"B", "c"=>"C");
$array2 = array("x"=>"X", "y"=>"X", "z"=>"Z");
$array3 = array("p"=>"P", "q"=>"Q", "r"=>"R");

$array[] = $array1;
$array[] = $array2;
$array[] = $array3;

echo json_encode($array);

?>
于 2013-10-24T10:29:59.940 に答える