如何使用JSON数据填充UITableView?

时间:2015-03-05 14:52:38

标签: ios json uitableview nsmutablearray nsdictionary

我正在努力弄清楚我做错了什么。我基本上试图用json数据填充我的UITableView。在控制台中我可以看到结果,但只是不知道为什么数据不会显示在tableview中。我看过类似的问题和答案,但没有一个能解决我的问题。

建议或帮助;

#pragma mark - Private method implementation

-(void)loadData{
    // Form the query.
    @try {


        NSString *get =[[NSString alloc] initWithFormat:@""];
        NSString *getRegions = [NSString stringWithFormat:@"JSON URL HERE",self.sessionId, self.companyId];
        NSURL *url=[NSURL URLWithString:getRegions];
        NSLog(@"Get regions: %@", url);
        NSData *postData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"GET"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setHTTPBody:postData];

        //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Reponse code: %ld", (long)[response statusCode]);
        if ([response statusCode] >= 200 && [response statusCode] < 300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);
            @try{
                NSError *error = nil;
                regionsJson = [[NSMutableArray alloc]init];
                //[jsonData removeAllObjects];
                regionsJson = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];

                NSArray *tblArray = [NSArray arrayWithObject:regionsJson];
            }
            @catch (NSException *e){
                NSLog(@"Try catch block: %@", e);
            }
            @finally{
                // [self.tblRegion reloadData];
                NSLog(@"finally");
            }


            structureJson =[regionsJson valueForKey:@"structure"];
            companyJson =[structureJson valueForKey:@"company"];
            _barBtnCompanyName.title = [companyJson valueForKey:@"company_name"];
            NSLog(@"Get company name: %@", [companyJson valueForKey:@"company_name"]);

            for  (int i =0 ; i < regionsJson.count; i++){
                regionsJson = [companyJson objectForKey:@"regions"];
                NSString *regionName = [NSString stringWithFormat:@"%@", [regionsJson valueForKey:@"region_name"]];
                NSLog(@"Region name: %@",regionName);
                // [regionsJson addObject:regionName];
                 NSString *alarmCount = [NSString stringWithFormat:@"%@", [regionsJson valueForKey:@"alarm_cnt"]];
                 NSLog(@"Alarm count: %@", alarmCount);
                 // [regionsJson addObject:alarmCount];

             }

        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);

    }
    // Reload the table view.
    [self.tblRegion reloadData];

}


#pragma mark - UITableView method implementation

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"Number of rows: %lu", (unsigned long)regionsJson.count);
    return [regionsJson count];

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CellRegions";
    // Dequeue the cell.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    // Set the loaded data to the appropriate cell labels.
     cell.textLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:@"region_name"];
     cell.detailTextLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:@"alarm_cnt"];

    [cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
    NSLog(@"Table cell: %@", cell);
    return cell;
}

1 个答案:

答案 0 :(得分:0)

我的代码很好,我做了一个愚蠢的遗漏。

-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tblRegion.delegate = self;
self.tblRegion.dataSource = self;
 [self loadData];

}