Count number of values in dictionary object - ios

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

Related

Program flow issues in ios

I am parsing a json to display the contents in the tableview. I have the array containing parsed json being populated in getReceivedData which is called after the UITAbleView Delegate methods. So it is problem in populating tableview as when the compiler attempts to populate it the array is not yet initialized.
- (void)getReceivedData:(NSMutableData *)data sender:(RestAPI *)sender{
NSError * error=nil;
NSArray *receivedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSString *dictionaryKey=#"department";
NSString *predicateString=#"software";
NSPredicate *predicate=[NSPredicate predicateWithFormat:#" %K == %# ", dictionaryKey,predicateString];
NSArray *shortlisted=[receivedData filteredArrayUsingPredicate:predicate];
for(int i = 0; i<shortlisted.count; i++)
{
NSDictionary *detailItems=[shortlisted objectAtIndex:i];
NSString *name=[detailItems objectForKey:#"emp_name"];
NSString *designation=[detailItems objectForKey:#"designation"];
NSString *email=[detailItems objectForKey:#"email"];
NSString *phone_no=[detailItems objectForKey:#"phone_no"];
// NSString *image=[detailItems objectForKey:#"url_path"];
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name, #"keyname",
designation, #"keydesignation",
email, #"keyid",
phone_no, #"keyphone",
nil];
[myObject1 addObject:dictionary1];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section{
if(isfiltered==YES){
return [filteredArray count];
}
else{
return [myObject1 count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MyTableCell *cell=[tableView dequeueReusableCellWithIdentifier:#"myCell"];
if(!cell){
[tableView registerNib:[UINib nibWithNibName:#"MyTableCell" bundle:nil]
forCellReuseIdentifier:#"myCell"];
cell=[tableView dequeueReusableCellWithIdentifier:#"myCell"];
}
if(isfiltered==NO)
{
NSDictionary * tmpdict= [myObject objectAtIndex:indexPath.row];
cell.nameLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyname"]];
cell.designationLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keydesignation"]];
cell.idLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyid"]];
cell.phoneLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyphone"]];
cell.mainImg.image = [UIImage imageNamed:[tmpdict objectForKeyedSubscript:#"keyimage"]];
}
else{
NSDictionary * tmpdict= [filteredArray objectAtIndex:indexPath.row];
cell.nameLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyname"]];
cell.designationLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keydesignation"]];
cell.idLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyid"]];
cell.phoneLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyphone"]];
cell.mainImg.image = [UIImage imageNamed:[tmpdict objectForKeyedSubscript:#"keyimage"]];
}
return cell;
}
This window was supposed to view the table
In a mutable dictionary first you have to give object then its key. You are doing wrong
for(int i = 0; i<shortlisted.count; i++)
{
NSDictionary *detailItems=[shortlisted objectAtIndex:i];
NSString *name=[detailItems objectForKey:#"emp_name"];
NSString *designation=[detailItems objectForKey:#"designation"];
NSString *email=[detailItems objectForKey:#"email"];
NSString *phone_no=[detailItems objectForKey:#"phone_no"];
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name,#"keyname",
designation,#"keydesignation",
email,#"keyid",
phone_no,#"keyphone",
nil];
[myObject1 addObject:dictionary1];
}
Actually this is not correct way to intialize dictionary as you did, #"%#" is used %# is a placeholder in a format string for any object.
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name,#"keyname",
designation,#"keydesignation",
email,#"keyid",
phone_no,#"keyphone",
nil];

Issue with getting the data from url Objective C

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.

How to bind NSDictionary data to table view in objective c?

I have used the below code to convert the JSON data(from SOAP service) to NSDictionary.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
}
Output
2017-04-04 13:03:51.085 SoapService[18444:588594] (
{
firstName = "1 Jhon";
lastName = Macay;
},
{
firstName = "2 William";
lastName = Proter;
},
{
firstName = "3 Joe";
lastName = Root;
},
{
firstName = "4 Brendon";
lastName = Haejoy;
},
{
firstName = "5 Jhon";
lastName = Snow;
},
{
firstName = "6 Theon";
lastName = Greyjoy;
}
)
Do I need to convert this to any other? or how could I bind the above output in UITable​View?
To work with table view you need array
Checkout this simple table view tutorial
It should be like this
Declare jsonArray in your .h file
#property (strong, nonatomic) NSMutableArray *jsonArray;
Add below line viewDidLoad
self.jsonArray = [[NSMutableArray alloc]init];
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",son);
[self.jsonArray addObject:[[json objectForKey:#"firstname"]stringByAppendingString:[json objectForKey:#"lastname"]];
[tableViewName reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [self.jsonArray objectAtIndex:indexPath.row];
return cell;
}
take one NSMutuableArray and add dictionary to this array like
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: json];
//Than Reload Tableview
Note: Declare array Globally to access in your class
tableview display data like
cell.label.text = [[array objectAtIndex:indexPath.row]valueForKey:#"firstName"];
Store json data into Global Declare NSArray.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
DataArray = [NSArray arrayWithObjects:json, nil];
[tableView reloadData];
}
Here DataArray is Globally Declare NSArray Object;
Now Write UITableView DataSource Method.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return DataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"jsoncell" forIndexPath:indexPath];
NSDictionary *dict = DataArray[indexPath.row];
NSString *output = [NSString stringWithFormat:#"%# %#",dict[#"firstName"],dict[#"lastName"]];
cell.textLabel.text = output;
return cell;
}

How do you load multiple arrays into a UITableView?

I am calling some JSON and loading a table with the data from a single array. That's working great. Now I'm trying to figure out
A. the best way to load the data into the table and
B. the best way to section that data off.
This is my 6th week of iOS development and I am pretty new. I have a fairly weak Javascript background.
My first (failed attempt) way to concatenate the arrays together and pass that to the tableview. I think this is wrong for multiple reasons (issues with sectioning afterwards, know "which" one to delete, etc). Any help is greatly appreciated!
Didn't work:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&errorJson];
self.allGroups = [dataDictionary objectForKey:#"all_groups"]; //NSDictionary
self.firstGroup = [self.allGroups objectForKey:#"first_group"]; //NSMutableArray
self.secondGroup = [self.allGroups objectForKey:#"second_group"]; //NSMutableArray
self.thirdGroup = [self.allGroups objectForKey:#"third_group"]; //NSMutableArray
NSMutableArray *allGroupsArray = [self.firstGroup arrayByAddingObjectsInArray:[self.secondGroup arrayByAddingObjectsInArray:self.thirdGroup]];
Does work now, but can't figure out multiple arrays into the tableview:
-(void) getTheData {
NSString *sessionToken = [[AFOAuthCredential retrieveCredentialWithIdentifier:#"myToken"] accessToken];
if (sessionToken == nil) {
LoginViewController *loginView = [[LoginViewController alloc] init];
[self presentViewController:loginView animated:NO completion:nil];
return;
}
NSURL *url = [NSURL URLWithString:#"https://greatwebsitetogetdata.com"];
AFOAuth2Client *oauthClient = [AFOAuth2Client clientWithBaseURL:url clientID:#"MY_CLIENT" secret:#"1234567890abc"];
[oauthClient getPath:#"/api/v1/json" parameters:#{#"access_token": sessionToken} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *errorJson = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&errorJson];
self.allGroups = [dataDictionary objectForKey:#"all_groups"]; //This is a NSDictionary
self.firstGroup = [self.allGroups objectForKey:#"first_group"]; //This is a NSMutableArray
self.secondGroup = [self.allGroups objectForKey:#"second_group"]; //This is a NSMutableArray
self.thirdGroup = [self.allGroups objectForKey:#"third_group"]; //This is a NSMutableArray
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.firstGroup.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *groupInfo = self.firstGroup[indexPath.row];
static NSString *cellIdentifier = #"Cell";
groupTableViewCell *cell = (groupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[groupTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.groupTitle.text= groupInfo[#"title"];
cell.groupLikes.text= [NSString stringWithFormat:#"%#", groupInfo[#"likes"]];
cell.groupRunDates.text= [NSString stringWithFormat:#"%# - %#", groupInfo[#"start_date"], groupInfo[#"end_date"]];
cell.groupAcceptance.text= groupInfo[#"acceptance_type"];
return cell;
}
I think an array of arrays would work better for you, where each array represents a section. allGroups should then contain 3 arrays.
Then you need to override the datasource method:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.allGroups.count;
}
and then in:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.allGroups[section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *group = self.allGroups[indexPath.section];
NSDictionary *groupInfo = group[indexPath.row];
static NSString *cellIdentifier = #"Cell";
groupTableViewCell *cell = (groupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[groupTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.groupTitle.text= groupInfo[#"title"];
cell.groupLikes.text= [NSString stringWithFormat:#"%#", groupInfo[#"likes"]];
cell.groupRunDates.text= [NSString stringWithFormat:#"%# - %#", groupInfo[#"start_date"], groupInfo[#"end_date"]];
cell.groupAcceptance.text= groupInfo[#"acceptance_type"];
return cell;
}

Parse JSON correctly for table view cell

I'm parsing JSON from my API which works fine but every time I select a row and get to the detail view he shows me the product with is supposed to be linked to the product shown at the very bottom. I don't understand why it isn't parsing the product id for the specific row because I have set it to parse for indexPath.row
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *neuheitenCell = #"neuheitenCell";
CJHomeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:neuheitenCell];
wareID = [[arrayArtikelWareID objectAtIndex:indexPath.row] objectForKey:#"ware_id"];
NSLog(#"Waren ID: %#", wareID);
cell.artikelName.text = [[arrayArtikelName objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.artikelHersteller.text = [[arrayArtikelHersteller objectAtIndex:indexPath.row] objectForKey:#"lieferant_name"];
return cell;
}
**EDIT:
-(void) parseJSONWithURL: (NSURL *) jsonURL {
dispatch_async(mainThreadQueue, ^{
NSError *error = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *json =[NSString stringWithContentsOfURL:jsonURL encoding:NSUTF8StringEncoding error:&error];
if (error == nil) {
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
dictionaryNewStuff = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
if (error == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
arrayNeuheiten = [[dictionaryNewStuff valueForKey:#"newstuff"] valueForKey:#"Neuheiten"];
arrayArtikelBild = [[dictionaryNewStuff valueForKey:#"newstuff"] valueForKey:#"Neuheiten"];
[neuheitenTableView reloadData];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
});
}
}
});
}
JSON can be viewed at my API
Does anyone know how to fix this?
Thanks in advance!
Could you try using following code ?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *neuheitenCell = #"neuheitenCell";
CJHomeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:neuheitenCell];
NSDictionary *object = [arrayNeuheiten objectAtIndex:indexPath.row];
NSString *wareID = [object objectForKey:#"ware_id"];
NSLog(#"Waren ID: %#", wareID);
cell.artikelName.text = [object objectForKey:#"name"];
cell.artikelHersteller.text = [object objectForKey:#"lieferant_name"];
return cell;
}
Why do you need two arrays for holding the data ? I mean following lines " arrayNeuheiten = [[dictionaryNewStuff valueForKey:#"newstuff"] valueForKey:#"Neuheiten"]; arrayArtikelBild = [[dictionaryNewStuff valueForKey:#"newstuff"] valueForKey:#"Neuheiten"]; "
Also where do you assign anything to arrayArtikelWareID ,arrayArtikelName ,arrayArtikelHersteller

Resources