2013-10-24 89 views
0

我在xCode中創建應用程序。我有一個從.json文件加載JSON數據的方法。這工作正常,我的viewcontroller顯示我的JSON對象(解析後)。代碼是:Objective C - 從.php文件加載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對象。我更改「http:// www .... .php」中的URL。我沒有錯誤,但它不加載JSON。我的viewcontroller不顯示數據。我試圖改變代碼中的許多東西,但沒有任何工作。如果我使用.php而不是.json url,那麼有人可以用loadJsonData的確切代碼來幫助我。

在此先感謝!

回答

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]]; 

得到JSON字符串它使用SBSON到的NSDictionary如下解析後

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

?>