Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从JSON填充表视图_Ios_Json_Uitableview - Fatal编程技术网

Ios 从JSON填充表视图

Ios 从JSON填充表视图,ios,json,uitableview,Ios,Json,Uitableview,我有一个NSString作为URL请求的结果 NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if(responseString && responseString.length) { //

我有一个NSString作为URL请求的结果

  NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   if(responseString && responseString.length) {
                                     //  NSLog(@"DATOS RECIBIDOS EN HISTORIAL=%@", responseString);
                                       NSError *jsonError;
                                       NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
                                      json = [NSJSONSerialization JSONObjectWithData:objectData
                                                                                            options:NSJSONReadingMutableContainers
                                                                                              error:&jsonError];
                                       NSArray *messageArray = [json objectForKey:@"objects"];

                                       // Parse and loop through the JSON
                                       for (json in messageArray) {
                                           NSString * code = [json objectForKey:@"code"];

                                           NSDictionary *level2Dict = [json objectForKey:@"client"];
                                           NSString *email =  [level2Dict objectForKey:@"email"];

                                           //NSString * nombre = someObject;
                                           NSLog(@"CODIGO DE CLIENTE=%@",code);
                                           NSLog(@"EMAIL DEL CLIENTE=%@",email);

                                       }
然后我将该字符串转换为NSData,并将其反序列化为json字符串。 稍后,我可以迭代字典数组,从一些json对象获取值

但是几个小时以来,我一直试图将所有这些信息传递给表视图,但我无法。从上面的代码中,我应该做什么来获得在表视图上显示的所需信息

多谢各位

编辑问题:

@interface HistorialReservasViewController () {
       NSArray *messageArray;
}

@end

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
    self.navigationItem.leftBarButtonItem=newBackButton;
    self.title = @"Corona";



    //REQUEST DEL HISTORIAL
    messageArray = [[NSArray alloc] init]; // just so array is not nil


    //1. client , lo tomamos de la variable del sistema
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];//se crea una instancia de la variable del sistema

    //LOS PARAMETROS NECESARIOS SON client y date


    //buscamos client
    NSString *idcliente = [defaults objectForKey:@"idUsuario"];
    NSLog(@"ID CLIENTE=&%@",idcliente);
    NSString *cliente = idcliente;



    NSDateFormatter *formatter;
    NSString        *dateString;

    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    dateString = [formatter stringFromDate:[NSDate date]];
    NSLog(@"FECHA=%@", dateString);

    NSString *fecha = dateString;

    NSLog(@"CLIENTE=%@",cliente);
    NSLog(@"FECHA=%@",fecha);


    //request


    NSURL *apiURL = [NSURL URLWithString:
                     [NSString stringWithFormat:@"http://hidden here/?client=%@&date=%@", cliente,fecha]];
    NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               if(data.length) {
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   if(responseString && responseString.length) {
                                     //  NSLog(@"DATOS RECIBIDOS EN HISTORIAL=%@", responseString);
                                       NSError *jsonError;
                                       NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
                                      json = [NSJSONSerialization JSONObjectWithData:objectData
                                                                                            options:NSJSONReadingMutableContainers
                                                                                              error:&jsonError];
                                          messageArray = [json objectForKey:@"objects"];

                                       // Parse and loop through the JSON
                                       for (json in messageArray) {
                                           NSString * code = [json objectForKey:@"code"];

                                           NSDictionary *level2Dict = [json objectForKey:@"client"];
                                           NSString *email =  [level2Dict objectForKey:@"email"];
                                       //   id someObject = [level2Dict objectForKey:@"name"];
                                         //  NSLog(@"NOMBRE===%@",someObject);
                                           //NSString * nombre = someObject;
                                           NSLog(@"CODIGO DE CLIENTE=%@",code);
                                           NSLog(@"EMAIL DEL CLIENTE=%@",email);

                                       }



                                   }
                               }
                           }];

    NSLog(@"NUMERO ED ITEMS=%lu", (unsigned long)messageArray.count);



}




//METODOS PARA LA CONEXION



-(void)home:(UIBarButtonItem *)sender {
   [self performSegueWithIdentifier:@"mapa_segue" sender:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return [messageArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    cell.textLabel.text = [[messageArray objectAtIndex:indexPath.row] objectForKey:@"code"];
    return cell;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

    return NO;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

}

您根本没有将数据传递到tableview。您需要创建全局数组并在viewDidLoad中初始化该数组,像您一样填充它,然后在tableview函数中使用它

NSArray *messageArray;
鉴于此,负载是否改变了这条线路

-(void)viewDidLoad{
    messageArray = [[NSArray alloc] init]; // just so array is not nil
    messageArray = [json objectForKey:@"objects"];
}
并使用此数组填充tableview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return [messageArray count]; //this will ensure you will have as many cells in your table view as there are values in your array
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    //here you use your array and fill cell with your data
    // you need to have a UILabel in cell which is called "codeLabel" but feel free to name it whatever you want
    cell.codeLabel.text = [[messageArray objectAtIndex:indexPath.row] objectForKey:@"code"]; //to fill your codelabel with code value from array
    cell.otherLabel.text = [[messageArray objectAtIndex:indexPath.row] objectForKey:@"other"]; //just another value

    return cell;
}
编辑
如何创建tableview?您是否设置了委托和数据源并实现了所需的功能?请也为这些方法提供代码。@IxPaka,谢谢,您在上面看到的是viewDidLoad方法的内部,所有其他与表视图相关的方法也在那里。表已显示,但显然是空的。谢谢。我已经实现了你的代码,但是messageArray.count=0。@user4619034哦,我忘了,你需要重新加载tableview当你填充数组时,添加
[yourTableView reloadData]
viewDidLoad函数的末尾,您是对的,但是messageArray.count在任何情况下都是0。@user4619034尝试这样填充它
messageArray=[NSArray arrayWithArray:[json objectForKey:@“objects”]相同的结果,messageArray.count=0
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                           if(data.length) {
                               NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                               if(responseString && responseString.length) {
                                 //  NSLog(@"DATOS RECIBIDOS EN HISTORIAL=%@", responseString);
                                   NSError *jsonError;
                                   NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
                                  json = [NSJSONSerialization JSONObjectWithData:objectData
                                                                                        options:NSJSONReadingMutableContainers
                                                                                          error:&jsonError];
                                      messageArray = [json objectForKey:@"objects"];
                                      NSLog(@"NUMERO ED ITEMS=%lu", (unsigned long)messageArray.count);
                                     //all UI updates must be called from main thread, thats why reload data must be wrapped in this call for more info google "ios GCD"
                                     dispatch_async(dispatch_get_main_queue){
                                         [tableView reloadData];
                                     }

                                   // Parse and loop through the JSON
                                   for (json in messageArray) {
                                       NSString * code = [json objectForKey:@"code"];

                                       NSDictionary *level2Dict = [json objectForKey:@"client"];
                                       NSString *email =  [level2Dict objectForKey:@"email"];
                                   //   id someObject = [level2Dict objectForKey:@"name"];
                                     //  NSLog(@"NOMBRE===%@",someObject);
                                       //NSString * nombre = someObject;
                                       NSLog(@"CODIGO DE CLIENTE=%@",code);
                                       NSLog(@"EMAIL DEL CLIENTE=%@",email);

                                   }



                               }
                           }
                       }];