Issue with getting the data from url Objective C - ios

I have an issue with the below service.
{
"DataTable": [
{
"EmpTable": [
{
"Name": "Rakesh",
"Finaldata": "5",
"data": "One Year Free",
"heading": "HR",
},
{
"Name": "Roshan",
"Finaldata": "1",
"data": "1 Month",
"heading": "Software",
},
{
"Name": "Ramesh",
"Finaldata": "5",
"data": "3 Month",
"heading": "Admin",
},
]
}
]
}
Only getting the details of Ramesh from the above output, Remaining data doesn't display in my table view. Below is my code what i have tried from the above service. Please help to find out the issue. TIA
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _empArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
EmpCell *cell = (MembershipCell *) [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MembershipCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (EmpCell *) currentObject;
}
}
}
profiledict = [_empArr objectAtIndex:indexPath.row];
for (NSDictionary *temp in profiledict) {
cell.lblName.text = [temp objectForKey:#"Name"];
cell.lblFinaldata.text = [temp objectForKey:#"Finaldata"];
cell.lbldata.text = [temp objectForKey:#"data"];
cell.lblheading.text = [temp objectForKey:#"heading"];
}
return cell;
}
- (void)jsonData:(NSDictionary *)jsonDict
{
NSMutableArray *jsonArr;
NSMutableDictionary *dict;
[SVProgressHUD dismiss];
jsonArr=[jsonDict objectForKey:#"DataTable"];
if (![jsonArr isEqual:[NSNull null]]) {
_empArr=[[NSMutableArray alloc] init];
for (int i=0; i<jsonArr.count; i++) {
dict=[jsonArr objectAtIndex:i];
[_empArr addObject:[dict objectForKey:#"EmpTable"]];
}
[self.tableView reloadData];
}
else
{
[SVProgressHUD showErrorWithStatus:#"Something went wrong"];
[self.tableView reloadData];
}
}

You are adding Whole EmpTable array as an object in array. So there is only one object in array. Thats why only one cell will be added on tableView. Try to extract array objects from EmpTable array.
In - (void)jsonData:(NSDictionary *)jsonDict method
Replace
[_empArr addObject:[dict objectForKey:#"EmpTable"]];
with
[_empArr addObjectsFromArray:[dict objectForKey:#"EmpTable"]];
and in cellForRowAtIndexPath
Replace
profiledict = [_empArr objectAtIndex:indexPath.row];
for (NSDictionary *temp in profiledict) {
cell.lblName.text = [temp objectForKey:#"Name"];
cell.lblFinaldata.text = [temp objectForKey:#"Finaldata"];
cell.lbldata.text = [temp objectForKey:#"data"];
cell.lblheading.text = [temp objectForKey:#"heading"];
}
With
profiledict = [_empArr objectAtIndex:indexPath.row];
cell.lblName.text = [profiledict objectForKey:#"Name"];
cell.lblFinaldata.text = [profiledict objectForKey:#"Finaldata"];
cell.lbldata.text = [profiledict objectForKey:#"data"];
cell.lblheading.text = [temp objectForKey:#"heading"];
Hope this helps.

_empArr.count will always be 1 because you have only one "EmpTable" object inside. Even if you fix that, then in cellForRowAtIndexPath's for (NSDictionary *temp in profiledict) you cycle through all the array and never stop, so each time it will be the last object to fill your cell fields.

Related

How to create UITableViewCell in category wise arrange JSON objects

I want to like this, Please have a look
I have UITableViewCell and I create category wise arrange JSON data. I fetched all our value but how to arrange category inside particular array, like this first category "Automotive" in side "business_details" under two different-different array. I want to arrange category in UITableViewCell. how it possible, please help. Thank You
JSON
{
"status": [
{
"business_category_name": "Automotive",
"business_details": [
{
"img_url": "http:\/\/edutimeapp.com\/toshow\/chamber-of-commerc\/member-logo\/1467813900-263.jpg",
"name": "ssmpl",
"des": "SIXTH SENSE MARKETING PVT LTD",
"address": "m2",
"email": "hr#sixthsenseit.com",
"phone": "09999999999",
"member_since": "2016-07-06",
"img_company": "http:\/\/edutimeapp.com\/toshow\/chamber-of-commerc\/member-logo\/1467813900-263.jpg",
"website": "www.sixthsenseit.com",
"city": "indore",
"state": "mp",
"zip": "452001"
},
{
"img_url": "http:\/\/edutimeapp.com\/toshow\/chamber-of-commerc\/member-logo\/1467814186-DSC_5854.jpg11.jpg",
"name": "h",
"des": "",
"address": "gkjg",
"email": "jgjg",
"phone": "gjg",
"member_since": "2016-07-06",
"img_company": "http:\/\/edutimeapp.com\/toshow\/chamber-of-commerc\/member-logo\/1467814186-DSC_5854.jpg11.jpg",
"website": "jg",
"city": "jg",
"state": "gjg",
"zip": "jgj"
}
]
},
{
"business_category_name": "Banks\/Credit Unions\/Landers",
"business_details": [
{
"img_url": "http:\/\/edutimeapp.com\/toshow\/chamber-of-commerc\/member-logo\/1464667619-pnc.jpg",
"name": "PNC Bank",
"des": "PNC offers a wide range of services for all our customers, from individuals and small businesses, to corporations and government entities",
"address": "",
"email": "andrea.kendall#pnc.com",
"phone": "260-422-5922",
"member_since": "2016-05-31",
"img_company": "http:\/\/edutimeapp.com\/toshow\/chamber-of-commerc\/member-logo\/1464667619-pnc.jpg",
"website": "",
"city": "Fort Wayne",
"state": "IN",
"zip": "46808"
}
]
}
]
}
My code
- (void)viewDidLoad
{
[super viewDidLoad];
names = [NSMutableArray new];
ntm= [NSMutableArray new];
adrsary=[NSMutableArray new];
phoneary=[NSMutableArray new];
emailary=[NSMutableArray new];
websiteary=[NSMutableArray new];
sensary=[NSMutableArray new];
desary=[NSMutableArray new];
image=[NSMutableArray new];
[self.tabel_view setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.php"]];
response =[[NSMutableData alloc]init];
[NSURLConnection connectionWithRequest:req delegate:self];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",json);
NSArray *statuses = [json objectForKey:#"status"];
for(NSDictionary *status in statuses){
NSString *bussiness_category=[status valueForKey:#"business_category_name"];
[names addObject:bussiness_category];
NSLog(#"busness details %#",names);
for(NSDictionary *details in [status objectForKey:#"business_details"])
{
NSString *name=[details valueForKey:#"name"];
[ntm addObject:name];
NSLog(#"name %#",ntm);
NSString *address=[details valueForKey:#"address"];
[adrsary addObject:address];
NSLog(#"address %#",adrsary);
NSString *phone=[details valueForKey:#"phone"];
[phoneary addObject:phone];
NSLog(#"phone %#",phoneary);
NSString *email=[details valueForKey:#"email"];
[emailary addObject:email];
NSLog(#"email %#",emailary);
NSString *website=[details valueForKey:#"website"];
[websiteary addObject:website];
NSLog(#"website %#",websiteary);
NSString *memsens=[details valueForKey:#"member_since"];
[sensary addObject:memsens];
NSLog(#"mem. sense %#",sensary);
NSString *des=[details valueForKey:#"des"];
[desary addObject:des];
NSLog(#"desc. %#",desary);
NSString *img=[details valueForKey:#"img_url"];
[image addObject:img];
NSLog(#"image. %#",image);
}
}
for (int i=0; i<[names count]; i++) {
[arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
[self.tabel_view reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return names.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[arrayForBool objectAtIndex:section] boolValue]) {
return emailary.count;
}
else
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 70;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,70)];
sectionHeaderView.backgroundColor=[UIColor grayColor];
sectionHeaderView.tag=section;
UIView *sectionsubHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,60)];
sectionsubHeaderView.backgroundColor=[UIColor blueColor];
UIImageView *arrow=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0,60, 60)];
[arrow setImage:[UIImage imageNamed:#"arrow"]];
UILabel *Lbl=[[UILabel alloc]initWithFrame:CGRectMake(60, 0,tableView.frame.size.width-60, 60)];
Lbl.text=[names objectAtIndex:section];
Lbl.textColor=[UIColor whiteColor];
[sectionsubHeaderView addSubview:arrow];
[sectionsubHeaderView addSubview:Lbl];
[sectionHeaderView addSubview:sectionsubHeaderView];
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionHeaderView addGestureRecognizer:headerTapped];
return sectionHeaderView;
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
if (indexPath.row == 0) {
BOOL collapsed = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[names count]; i++) {
if (indexPath.section==i) {
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}
}
[self.tabel_view reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.title.text=[NSString stringWithFormat:#"%#",[ntm objectAtIndex:indexPath.row]];
cell.email.text=[NSString stringWithFormat:#"%#",[emailary objectAtIndex:indexPath.row]];
cell.address_lbl.text=[NSString stringWithFormat:#"%#",[adrsary objectAtIndex:indexPath.row]];
cell.phone_lbl.text=[NSString stringWithFormat:#"%#",[phoneary objectAtIndex:indexPath.row]];
cell.web_lbl.text=[NSString stringWithFormat:#"%#",[websiteary objectAtIndex:indexPath.row]];
cell.sens_lbl.text=[NSString stringWithFormat:#"%#",[sensary objectAtIndex:indexPath.row]];
cell.des_lbl.text=[NSString stringWithFormat:#"%#",[desary objectAtIndex:indexPath.row]];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [image objectAtIndex:indexPath.row]]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
cell.image_view.image =image;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
[self.tabel_view reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
}
try this-
take a global array i.e. NSMutableArray *arrayForBool; with your other array. Allocate this array in viewDidLoad() i.e. arrayForBool=[[NSMutableArray alloc]init];
Now add these lines of code in connectionDidFinishLoading just before
[tableview reloadData]-
for (int i=0; i<[names count]; i++) {
[arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
Here is complete code-
#import "ViewController.h"
#import "MemberTableViewCell.h"
#import "secondVC.h"
#interface ViewController ()
{
NSMutableData *response;
NSMutableArray *arrayForBool;
NSMutableArray *business_details_array;
NSMutableArray *names;
NSDictionary *passDict;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
names = [NSMutableArray new];
arrayForBool=[[NSMutableArray alloc]init];
[self.tableView setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.php"]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if( connection )
{
response = [NSMutableData new];
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response1
{
[response setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[response appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSArray *statuses = [json objectForKey:#"status"];
names=[[NSMutableArray alloc]initWithArray:[statuses valueForKey:#"business_category_name"]];
business_details_array=[[NSMutableArray alloc]initWithArray:[statuses valueForKey:#"business_details"]];
for (int i=0; i<[names count]; i++) {
[arrayForBool addObject:[NSNumber numberWithBool:NO]];
}
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return names.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[arrayForBool objectAtIndex:section] boolValue]) {
return [[business_details_array objectAtIndex:section] count];
}
else
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 70;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,70)];
sectionHeaderView.backgroundColor=[UIColor grayColor];
sectionHeaderView.tag=section;
UIView *sectionsubHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width,60)];
sectionsubHeaderView.backgroundColor=[UIColor blueColor];
UIImageView *arrow=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0,60, 60)];
[arrow setImage:[UIImage imageNamed:#"arrow.png"]];
UILabel *Lbl=[[UILabel alloc]initWithFrame:CGRectMake(60, 0,tableView.frame.size.width-60, 60)];
Lbl.text=[names objectAtIndex:section];
Lbl.textColor=[UIColor whiteColor];
[sectionsubHeaderView addSubview:arrow];
[sectionsubHeaderView addSubview:Lbl];
[sectionHeaderView addSubview:sectionsubHeaderView];
UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(sectionHeaderTapped:)];
[sectionHeaderView addGestureRecognizer:headerTapped];
return sectionHeaderView;
}
- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
if (indexPath.row == 0) {
BOOL collapsed = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
for (int i=0; i<[names count]; i++) {
if (indexPath.section==i) {
[arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
}
}
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.title.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"name"] objectAtIndex:indexPath.row]];
cell.email.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"email"] objectAtIndex:indexPath.row]];
cell.address_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"address"] objectAtIndex:indexPath.row]];
cell.phone_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"phone"] objectAtIndex:indexPath.row]];
cell.web_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"website"] objectAtIndex:indexPath.row]];
cell.sens_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"member_since"] objectAtIndex:indexPath.row]];
cell.des_lbl.text=[NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"des"] objectAtIndex:indexPath.row]];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"%#",[[[business_details_array objectAtIndex:indexPath.section] valueForKey:#"img_url"] objectAtIndex:indexPath.row]]]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
cell.image_view.image =image;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
passDict=[[business_details_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
[self performSegueWithIdentifier:#"gotoSeconVC" sender:self];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"gotoSeconVC"]) {
secondVC *vc=[segue destinationViewController];
vc.myPreviousVCDict=passDict;
}
}
#end
Now in secondVC.h file-
#import <UIKit/UIKit.h>
#interface secondVC : UIViewController
#property(strong,nonatomic)NSDictionary *myPreviousVCDict;
#end
NSLog() this dictionaty in viewDidLoad(). Hope this will help you. Using this you can make custom header of Section and expandable section.
Here is the output screen-
storyBoard must Look like this-
and this is member_details what you want--

I am trying to display detail list of may json response in UITableViewcell

Hi I am trying to display detail information of json data in second table view but their is some mistake in my logic so please help me my json response is in image and I am trying to to dispaly channel response in table view when user click the same cat_id then display all related channel list and image in second tableViewcell please help me..
-(void)getCategories
{
Service *srv=[[Service alloc]init];
NSString *str=#"http://streamtvbox.com/site/api/matrix/";//?country_code=91&phone=9173140993&fingerprint=2222222222";
NSString *method=#"channels";
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[srv postToURL:str withMethod:method andParams:dict completion:^(BOOL success, NSDictionary *responseObj)
{
NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[responseObj valueForKey:#"categories"]];
arrayChannelList=[responseObj valueForKey:#"channels"];
NSLog(#"Array : %#",channels);
for (NSDictionary *dict in arrayChannelList)
{
//NSArray *tempTitle = [[NSArray alloc]init];
arrayCat_Id = [dict objectForKey:#"cat_id"];
}
tempArray = [[NSArray alloc]init];
tempArray = [dict allKeys];
for(int i=0; i<tempArray.count; i++)
{
[arrayCategories addObject:[dict valueForKey:[tempArray objectAtIndex:i]]];
}
NSLog(#"%#",arrayCategories);
[tblView reloadData];
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%lu",(unsigned long)[arrayCategories count]);
return arrayCategories.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"ChannelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [arrayCategories objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
DetailChannelsViewController *detailVC = (DetailChannelsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:#"DetailView"];
detailVC.channelTitle = [arrayCategories objectAtIndex:indexPath.row];
detailVC.SubChannelName = arrayCat_Id;
NSLog(#"%#",arrayCat_Id);
[self.navigationController pushViewController:detailVC animated:YES];
}
Just initialize of your NSmutuableArray and add the value of with addobject like:-
arrayCat_Id=[[NSMutableArray alloc]init];
for(your logic){
[arrayCat_Id addobject:[dict objectForKey:#"cat_id"];
}

UITableViewController with Json

i'm trying to fill a tableview with a Json response this is the Json that i'm reading from the callback
{
"Categories": {
"Beer": [
{
"id": "3",
"nombre": "Bud ligth",
"precio": "10",
"categoriaid": "3",
"url": "false"
}
],
"Whiskey": [
{
"id": "2",
"nombre": "Red label",
"precio": "100",
"categoriaid": "2",
"url": "false"
}
]
}
}
and this is my code but it breaks the app any ideas on how can i make change my code in order to make it fill the tableview with its correspondent section and rows in each sections
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.menuInfo options:NSJSONReadingMutableContainers error:nil];
NSDictionary *cat = [json objectForKey:#"Categories"];
for(NSString *categories in cat){
Categorias *categorias = [[Categorias alloc]initWithNombre:categories];
NSDictionary *listTagDict = [cat objectForKey:categories];
for (NSString *prod in listTagDict) {
NSArray *rows = [listTagDict objectForKey:prod];
for (NSDictionary *rowDict in rows) {
NSString* pID = [rowDict objectForKey:#"id"];
NSString* pNombre = [rowDict objectForKey:#"nombre"];
NSString* pPrecio = [rowDict objectForKey:#"precio"];
NSString* pUrl = [rowDict objectForKey:#"url"];
Productos* productos = [[Productos alloc]initWithNombre:pNombre productoID:pID precio:pPrecio iconUrl:pUrl];
[categorias addRow:productos];
}
}
}
here are my two object clases the .m part
#implementation Productos
-(id)initWithNombre:(NSString *)name productoID:(NSString *)pId precio:(NSString*)prec iconUrl:(NSString*)url{
self = [super init];
if (self) {
self.nombre = name;
self.productoID = pId;
self.precio = prec;
self.iconUrl = url;
}
return self;
}
#end
#interface Categorias(){
NSMutableArray *rows;
}
#end
#implementation Categorias
-(id)initWithNombre:(NSString *)name{
self = [super init];
if (self) {
self.nombre = name;
}
return self;
}
-(void)addRow:(Productos *)row {
[rows addObject: row];
}
-(NSArray *)rowData {
return [NSArray arrayWithArray: rows];
}
#end
you are parsing the json response in wrong way,
try this,
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.menuInfo options:NSJSONReadingMutableContainers error:nil];
NSDictionary *cat = [json objectForKey:#"Categories"];
NSMutableArray *categoryArray = [NSMutableArray new];
for(NSString *key in [cat allKeys]){
Categorias *category = [[Categorias alloc]initWithNombre:key];
NSArray *listTagDict = [cat objectForKey:key];
for (NSDictionary *prod in listTagDict) {
NSString* pID = [prod objectForKey:#"id"];
NSString* pNombre = [prod objectForKey:#"nombre"];
NSString* pPrecio = [prod objectForKey:#"precio"];
NSString* pUrl = [prod objectForKey:#"url"];
Productos* productos = [[Productos alloc]initWithNombre:pNombre productoID:pID precio:pPrecio iconUrl:pUrl];
[category addRow:productos];
}
[categoryArray addObject:category];
}
use categoryArray to populate tableview.
in this, categoryArray count will be section count, and each section contains rows with rowData array of each category.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [categoryArray count];
}
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
Category *category = [categoryArray objectAtIndex:section];
return category.nombre;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
Category *category = [categoryArray objectAtIndex:section];
NSArray *rows = [category rowData];
return [rows count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath]; return cell;
Category *category = [categoryArray objectAtIndex:indexPath.section];
NSArray *rows = [category rowData];
Product *product = [rows objectAtIndex:indexPath.row];
//populate cell with product
}

Cell for row at indexpath only called once

I am parsing a json data and in that one of the field is an array if it has a content.But if it has no content it is simply a string "No result."
I am using the following code to parse it :
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
//URL is called.
if ([status isEqualToString:#"success"])
{
if ([[[json objectForKey:#"Items"] objectForKey:#"item_list"] isKindOfClass:[NSString class]])
{
_Label.text = [NSString stringWithFormat:#"0"];
ItemsArray = [[NSMutableArray alloc]init];
}
else
{
ItemsArray = [[json objectForKey:#"Items"] objectForKey:#"item_list"];
NSLog(#"%d",[ItemsArray count]);
float Amount = 0;
NSLog(#"%d",[ItemsArray count]);
if ([ItemsArray count]>0)
{
for (int i=0; i<[ItemsArray count]; i++)
{
NSMutableDictionary * temp3 = [ItemsArray objectAtIndex: i];
NSString * x = [temp3 objectForKey:#"final"];
Amount = Amount + [x floatValue];
}
Label.text = [NSString stringWithFormat:#"%.2f",BidAmount];
}
else
{
Label.text = [NSString stringWithFormat:#"0"];
}
}
[TableViewOutlet reloadData];
}
This works fine.
When the field returns string i face no problem.But when the field is an array,I am stuck.
After running the project for the first time it works fine even if the array count is more than 0.But from second time onwards the Cellforrowatindexpath method is not called even when array count is more than 0....
These are my codes:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d",[ItemsArray count]);
return [ItemsArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.025];
NSDictionary *temp = [ItemsArray objectAtIndex:indexPath.row];
UILabel *ItemName = (UILabel *)[cell viewWithTag:1000];
ItemName.text = [temp objectForKey:#"title"];
UILabel *Cost = (UILabel *)[cell viewWithTag:1001];
Cost.text = [temp objectForKey:#"final"];
return cell;
}
Someone please help me
I think the issue is that you have not retained your ItemArray.
NSArray* array = [[json objectForKey:#"Items"] objectForKey:#"item_list"];
ItemsArray = [NSMutableArray alloc]]initWithArray:array];
Use this code snippet..hope it will work.

Count number of values in dictionary object

<pre>
products = (
{
id = 19;
"image_url" = "http://localhost:8888/straightoffer/image/data/1330374078photography.jpg";
name = "Save $240 on your next photo session";
},
{
id = 21;
"image_url" = "http://localhost:8888/straightoffer/image/data/1330373696massage.jpg";
name = "One Hour Massage";
}
);
}
</pre>
the above is what I got through json, I need to assign the values to uitableviews:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"Number of rows: %d",[[products objectForKey:#"products"] count]);
return [[products objectForKey:#"products"] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"cell"];
}
NSString *currentProductName;
currentProductName = [productKeys objectAtIndex:indexPath.row];
NSLog(#"product name : %#", currentProductName);
[[cell textLabel] setText:currentProductName];
return cell;
}
it returns 0 number of rows, I am newbie to ios please help me how I will assign these values to uitableview.
Regards
The problem is that what you posted is not json. It should be
{
"products":[
{
"id":19,
"image_url":"http://localhost:8888/straightoffer/image/data/1330374078photography.jpg",
"name":"Save $240 on your next photo session"
},
{
"id":21,
"image_url":"http://localhost:8888/straightoffer/image/data/1330373696massage.jpg",
"name":"One Hour Massage"
}
]
}
You can use http://jsonlint.com/ to validate your json files.
I have used the above json file and did the following:
NSBundle* bundle = [NSBundle mainBundle];
NSString *jsonPath = [bundle pathForResource:#"data" ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:jsonPath];
NSError *error;
NSDictionary *products = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
DLog(#"products: %i", [[products objectForKey:#"products"] count] );
[self.tableView reloadData];
Result is: products: 2.
You should be able to reproduce this.

Resources