2014-03-06 50 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