填充表格视图表格JSON

时间:2015-03-16 00:05:31

标签: ios json uitableview

我有一个NSString作为URLRequest的结果。

  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 {

}

1 个答案:

答案 0 :(得分:1)

您根本没有将数据传递到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;
}

修改

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

                                   }



                               }
                           }
                       }];