2014-03-06 51 views
0

我試着從PHP文件發送和檢索數據的不同代碼,我仍然無法正確地得到結果 到目前爲止,我得到的檢索結果顯示在輸出調試器(以json格式),但不在Xcode模擬器中。好像我錯過了一些東西!從Xcode的php文件檢索數據

- (void) retrieveData 
{ 



NSString * jack=[GlobalVar sharedGlobalVar].gUserName; 
NSLog(@"global variable %@", jack); 



NSString *rawStr = [NSString stringWithFormat:@"StudentID=%@",jack]; 
NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding]; 

NSURL *url = [NSURL URLWithString:@"http://m-macbook-pro.local/studentCourses.php"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:data]; 

NSURLResponse *response; 
NSError *err; 
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; 
NSLog(@"responseData: %@", responseData); 

    jsonArray=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 

// Search for the array parameter that should be added 
coursesArray=[[NSMutableArray alloc] init]; 
//set up our cities array 

NSString *strResult = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSLog(@"me: %@", strResult); 



//loop through our json array 

for (int i = 0 ; i <coursesArray.count; i++) 
{ 
    NSString * cName = [[coursesArray objectAtIndex:i] objectForKey:@"CourseName"]; 

    //Add the City object to our cities array 
    [coursesArray addObject:[[Course alloc]initWithCourseName:cName]]; 

} 

//Reload our table view 
[self.tableView reloadData]; 
} 
在PHP文件

echo json_encode($records); 

回答

0

它看起來像你與你的訊息數據創建JSON數組,而不是與來自服務器返回的responseData。

//change this 
jsonArray=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 
//to this 
jsonArray=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil]; 

此外,根據您發佈它看起來並不像你曾經添加從服務器到您的coursesArray返回的結果代碼。在你的循環中,你創建cName的地方,我想你要做的就是從php調用的結果(你的jsonArray)中獲取課程名稱,並將它們添加到你的課程數組中。您設置的方式是從課程數組中獲取結果並將其添加到自己。

試試這個代碼,您的for循環:基於

for (int i = 0 ; i <jsonArray.count; i++) 
{ 
    NSString * cName = [[jsonArray objectAtIndex:i] objectForKey:@"CourseName"]; 

    [coursesArray addObject:[[Course alloc]initWithCourseName:cName]]; 

} 

您的代碼我假設coursesArray包含您的tableview數據。

另請注意,在生產應用程序中使用同步請求時,在主線程上運行並阻止用戶界面不是一個好主意。

+0

感謝您的幫助,它解決了這個問題。但是,我可以問一下你的意思是「會阻止用戶界面」嗎? .. 因爲現在我們對另一個導航控制器使用相同的代碼,並且顯示錯誤(線程1:信號SIGABRT),請問同步請求是否會導致此類問題? – mimi12

+0

這意味着您的用戶界面在主線程上處理。如果您在主線程上執行Web請求,則用戶界面將凍結,直到請求完成加載。我不能說不知道它會導致你的崩潰。如果你無法弄清楚,我會建議發佈一個單獨的問題來解決它。 – digitalHound