简体   繁体   English

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

[英]How do I populate my UITableView with data from JSON array?

I have been trying to populate my tableView for the pas 4 days and I keep hitting dead ends. 我一直在尝试填充我的tableView达4天,而且我一直死胡同。

I have been through the questions on here and tried some of the suggestions that others have been given, but none of them seem to work. 我已经解决了这里的问题,并尝试了其他一些建议,但似乎都没有用。 Basically I have JSON data sent from my website and that is populating an array that I then wish to put into a tableView. 基本上,我有从我的网站发送的JSON数据,并且正在填充一个数组,然后将其放入tableView中。

The NSLog is returning all correct info, but seems to stop once the array is created, and doesn't have any data logging after the array populates. NSLog返回所有正确的信息,但似乎在创建数组后停止,并且在数组填充后没有任何数据记录。

here is my .h file 这是我的.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

and my .m file 和我的.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

and my NSLog output 和我的NSLog输出

2014-03-11 14:40:13.006 TESG-iConnect[29384:a0b] PostData: username=&password= 2014-03-11 14:40:13.119 TESG-iConnect[29384:a0b] Response code: 200 2014-03-11 14:40:13.119 TESG-iConnect[29384:a0b] Response ==> {"success":1} 2014-03-11 14:40:13.120 TESG-iConnect[29384:a0b] Success: 1 2014-03-11 14:40:13.120 TESG-iConnect[29384:a0b] Login SUCCESS 2014-03-11 14:40:14.677 TESG-iConnect[29384:a0b] Received Data: [{"id":"7684","title":"POT Feb 2011","date":"2011-04-18 10:49:27","link":"1303087767_POT 113 Lonsdale St feb11.pdf"},{"id":"7683","title":"Audit Feb 2011","date":"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, Melbourne 2011.pdf"},{"id":"8761","title":"Annual 2011","date":"2011-08-02 12:55:56","link":"1312253756_Annual Passive 113 Lonsdale St May 2011.pdf"},{"id":"8762","title":"Audit May 2011","date":"2011-08-02 12:56:16","link":"1312253775_CA 113 Lo 2014-03-11 14:40:13.006 TESG-iConnect [29384:a0b] PostData:用户名=&password = 2014-03-11 14:40:13.119 TESG-iConnect [29384:a0b]响应代码:200 2014-03- 11 14:40:13.119 TESG-iConnect [29384:a0b]响应==> {“成功”: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 2011年2月”,“日期”:“ 2011-04-18 10:49:27”,“链接”:“ 1303087767_POT 113 Lonsdale St feb11.pdf”},{“ id”:“ 7683”,“标题“:”“ Audit Feb 2011”,“ date”:“ 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,Melbourne 2011.pdf”},{“ id”:“ 8761 “,” title“:” Annual 2011“,” date“:” 2011-08-02 12:55:56“,” link“:” 1312253756_Annual Passive 113 Lonsdale St May 2011.pdf“},{” id“: “ 8762”,“标题”:“ 2011年5月审核”,“日期”:“ 2011-08-02 12:56:16”,“链接”:“ 1312253775_CA 113 Lo nsdale Street May 11.pdf"},{"id":"8763","title":"POT May 2011","date":"2011-08-02 12:56:34","link":"1312253794_POT 113 Lonsdale Street May 2011.pdf"},{"id":"10286","title":"Audit Aug 2011","date":"2011-11-08 14:31:34","link":"1320723094_CA 113 Lonsdale Street Aug 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] Array Populated 2014-03-11 14:40:14.678 TESG-iConnect[29384:a0b] 8 reports found nsdale Street May 11.pdf“},{” id“:” 8763“,” title“:” POT May 2011“,” date“:” 2011-08-02 12:56:34“,” link“:” 1312253794_POT 113 Lonsdale Street 2011年5月。pdf“},{” id“:” 10286“,” title“:” Audit Aug 2011“,” date“:” 2011-11-08 14:31:34“,” link“ :“” 1320723094_CA 113 Lonsdale Street Aug 11.pdf“},{” id“:” 10287“,” title“:” POT 2011年8月“,” date“:” 2011-11-08 14:31:46“,” link“:”“ 1320723106_POT 113 Lonsdale Street 2011年8月。pdf”}“] 2014-03-11 14:40:14.678 TESG-iConnect [29384:a0b]填充的阵列2014-03-11 14:40:14.678 TESG-iConnect [29384 :a0b]找到8个报告

I cannot seem to find where the code is not working. 我似乎找不到代码无法正常工作的地方。 can someone point me in the right direction please?? 有人可以指出我正确的方向吗?

EDIT TO INCLUDE dataObject JUST IN CASE 编辑以包含dataObject仅在情况下

//
//  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

You haven't initialised your uitableviewcell 您尚未初始化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];

    }

我认为您需要在setupReportsFromJSONArray方法的末尾而不是在didReceiveResponse中调用reloadData,因为您直到那时才创建reportsArray。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM