从 Xcode 中的 php 文件中检索数据



我尝试了不同的代码来发送和检索PHP文件中的数据,但我仍然无法正确获得结果到目前为止,我得到了要在输出调试器(以 json 格式)中显示的检索结果,而不是在 Xcode 模拟器中。好像我错过了什么!

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

看起来您正在使用帖子数据创建 json 数组,而不是使用从服务器返回的响应数据。

//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包含表视图的数据。

另请注意,在生产应用中使用同步请求不是一个好主意,因为它们在主线程上运行并且会阻止 UI。

最新更新