如何使用JSON数组中的数据填充UITableView?

时间:2014-03-11 03:51:03

标签: ios json uitableview

我一直在尝试填充我的tableView for the 4天,我一直在努力。

我在这里已经完成了一些问题,并尝试了其他人给出的一些建议,但似乎都没有。基本上我从我的网站发送了JSON数据,并填充了一个数组,然后我希望将其放入tableView中。

NSLog返回所有正确的信息,但似乎在创建数组后停止,并且在数组填充后没有任何数据记录。

这是我的.h文件

//
//  reportsTestViewController.h
//  TESG-iConnect
//
//  Created by TESG on 7/03/14.
//  Copyright (c) 2014 TESG. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface reportsTestViewController : UIViewController  <UITableViewDelegate, UITableViewDataSource>{

    IBOutlet UITableView *reportsTable;

    NSString *response;
    NSMutableArray *reportsArray;

}

@property (nonatomic, retain) NSString *response;

@property (nonatomic, strong) NSMutableData *myDataIvar;



@end

和我的.m文件

//
//  reportsTestViewController.m
//  TESG-iConnect
//
//  Created by TESG on 7/03/14.
//  Copyright (c) 2014 TESG. All rights reserved.
//

#import "reportsTestViewController.h"
#import "ReportsDataObject.h"

@interface reportsTestViewController ()

@end

@implementation reportsTestViewController

@synthesize response;

@synthesize myDataIvar;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

#pragma mark NSURLConnection Delegate Methods
//    

    //Create your request pointing to the test page
   NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.tesg.com.au/allCustBuild.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];


    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    //initialize it when you create your connection
    if (connection){
        self.myDataIvar = [[NSMutableData alloc] init];
    }
}

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        [self.myDataIvar setLength:0];
    }

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        [self.myDataIvar appendData:data];
        [reportsTable reloadData];
    }

    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
        NSLog(@"Connection Failed: %@", error.userInfo);
    }

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //this is where you would parse the data received back from the server
    NSString *responseString = [[NSString alloc] initWithData:self.myDataIvar encoding:NSUTF8StringEncoding];
    NSLog(@"Received Data: %@",responseString);
    [self setupReportsFromJSONArray:self.myDataIvar];

}

-(void)connectionWasASuccess:(NSData *)data{
    [self setupReportsFromJSONArray:data];
}



-(void)setupReportsFromJSONArray:(NSData*)dataFromReportsArray{
    NSError *error;
   // NSMutableArray *reportsArray = [[NSMutableArray alloc] init];
    NSArray *arrayFromServer = [NSJSONSerialization JSONObjectWithData:dataFromReportsArray options:0 error:&error];

    if(error){
        NSLog(@"error parsing the json data from server with error description - %@", [error localizedDescription]);
    }
    else {
        reportsArray = [[NSMutableArray alloc] init];
        for(NSDictionary *eachReport in arrayFromServer)
        {
            ReportsDataObject *report = [[ReportsDataObject alloc] initWithJSONData:eachReport];
            [reportsArray addObject:report];
        }
        NSLog(@"Array Populated");
        NSLog(@"%u reports found",reportsArray.count);
        //Now you have your reportsArray filled up with all your data objects
    }
}


-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //We check against table to make sure we are displaying the right number of cells
    // for the appropriate table. This is so that things will work even if one day you
    //decide that you want to have two tables instead of one.
//    if(tableView == reportsTable)
    {
        return([reportsArray count]);
    }
    return 0;
    NSLog(@"%u",reportsArray.count);
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reportsTableIdentifier = @"ReportsTableCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reportsTableIdentifier];
    if(cell)
    {
        //set your configuration of your cell
    }
    //The beauty of this is that you have all your data in one object and grab WHATEVER you like
    //This way in the future you can add another field without doing much.

    if([reportsArray count] == 0){
        cell.textLabel.text = @"no reports to show";
    }
    else{
        ReportsDataObject *currentReport = [reportsArray objectAtIndex:indexPath.row];
        cell.textLabel.text = [currentReport reportName];
        // in the future you can grab whatever data you need like this
        //[currentReport buildingName], or [currentReport reportName];
    }
    return(cell);
}

@end

和我的NSLog输出

  

2014-03-11 14:40:13.006 TESG-iConnect [29384:a0b] PostData:   username =&amp; password = 2014-03-11 14:40:13.119   TESG-iConnect [29384:a0b]回复代码:200 2014-03-11 14:40:13.119   TESG-iConnect [29384:a0b]响应==&gt; {“成功”:1} 2014-03-11   14:40:13.120 TESG-iConnect [29384:a0b]成功:1 2014-03-11   14:40:13.120 TESG-iConnect [29384:a0b]登录成功2014-03-11   14:40:14.677 TESG-iConnect [29384:a0b]收到的数据:   [{“id”:“7684”,“title”:“POT Feb 2011”,“date”:“2011-04-18   10:49:27“,”link“:”1303087767_POT 113 Lonsdale St.   feb11.pdf“},{”id“:”7683“,”title“:”2011年2月审计“,”日期“:”2011-04-18   10:49:12“,”link“:”1303087751_CA 113 Lonsdale St feb   11.pdf“},{”id“:”11189“,”title“:”AESMR 2011“,”date“:”2012-01-30 09:49:28“,”link“:”1327877368_AESMR 113 Lonsdale Street ,墨尔本   2011.pdf“},{”id“:”8761“,”title“:”2011年度“,”日期“:”2011-08-02 12:55:56“,”链接“:”1312253756_Annual Passive 113 Lonsdale圣梅   2011.pdf“},{”id“:”8762“,”title“:”Audit May 2011“,”date“:”2011-08-02 12:56:16“,”link“:”1312253775_CA 113 Lonsdale五月街   11.pdf“},{”id“:”8763“,”title“:”POT May 2011“,”date“:”2011-08-02 12:56:34“,”link“:”1312253794_POT 113 Lonsdale五月街   2011.pdf“},{”id“:”10286“,”title“:”Audit August 2011“,”date“:”2011-11-08 14:31:34“,”link“:”1320723094_CA 113 Lonsdale街8月   11.pdf“},{”id“:”10287“,”title“:”POT Aug 2011“,”date“:”2011-11-08 14:31:46“,”link“:”1320723106_POT 113 Lonsdale Street Aug 2011.pdf“}]   2014-03-11 14:40:14.678 TESG-iConnect [29384:a0b]阵列已填充   2014-03-11 14:40:14.678 TESG-iConnect [29384:a0b]发现8个报告

我似乎无法找到代码无法正常工作的地方。有人能指出我正确的方向吗??

编辑包含dataObject JUST IN CASE

//
//  ReportsDataObject.h
//  TESG-iConnect
//
//  Created by TESG on 7/03/14.
//  Copyright (c) 2014 TESG. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ReportsDataObject : NSObject

-(id)initWithJSONData:(NSDictionary*)data;

@property (assign) NSInteger reportId;
@property (strong) NSString *buildingName;
@property (strong) NSString *reportName;
@property (strong) NSString *reportDate;
@property (strong) NSString *reportLink;

@end

//
//  ReportsDataObject.m
//  TESG-iConnect
//
//  Created by TESG on 7/03/14.
//  Copyright (c) 2014 TESG. All rights reserved.
//

#import "ReportsDataObject.h"

@implementation ReportsDataObject

@synthesize reportId;
@synthesize buildingName;
@synthesize reportName;
@synthesize reportDate;
@synthesize reportLink;

-(id)initWithJSONData:(NSDictionary*)data{
    self = [super init];
    if(self){
        //NSLog(@"initWithJSONData method called");
        self.reportId = [[data objectForKey:@"id"] integerValue];
        self.buildingName =  [data objectForKey:@"buildingname"];
        self.reportName = [data objectForKey:@"reportname"];
        self.reportDate = [data objectForKey:@"reportdate"];
        self.reportLink = [data objectForKey:@"reportlink"];

    }
    return self;
}

@end

2 个答案:

答案 0 :(得分:0)

您尚未初始化您的uitableviewcell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier = @"Cell";

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {


        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

答案 1 :(得分:0)

我认为您需要在setupReportsFromJSONArray方法的末尾而不是didReceiveResponse中调用reloadData,因为在此之前您不创建reportsArray。