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;
}
Related
how to get all id's from this url and display in uitableview "http://www.thomas-bayer.com/sqlrest/CUSTOMER/".
- (void)viewDidLoad
{
NSURL *URL = [[NSURL alloc] initWithString:#"http://www.thomas-bayer.com/sqlrest/CUSTOMER/"];
NSString *xmlString = [[NSString alloc] initWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:NULL];
xmlDoc = [NSDictionary dictionaryWithXMLString:xmlString];
NSLog(#"dictionary: %#", xmlDoc);
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [xmlDoc count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.textLabel.text = [[[xmlDoc objectForKey:#"CUSTOMER"]objectAtIndex:indexPath.row]objectForKey:#"__text"];
return cell;
}
I am getting only 0,1,2 values displayed in uitableview and ignoring the remaining id's ?
Use this Library to convert XMLData into NSDictionary object.
https://github.com/nicklockwood/XMLDictionary then simply fetch your required data from NSDictionary object and update it into your TableView.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to get JSON to UITableView from a URL API.
Below is my code for my view controller.
I'm quite new to Objective-C.
Just wanting to know what I should use to make this happen. This is my code below and I keep getting errors.
Any help would be greatly appreciated.
Please remember I'm really new to this so I will need a detailed explanation and working through.
ViewController.h
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSError *error;
NSString *url_string = [NSString stringWithFormat: #"http://django-env2.55jfup33kw.us-west-2.elasticbeanstalk.com/api/Musician/?format=json"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//NSLog(#"json: %#", json);
// NSString *mystring = json[1];
// NSLog(#"json: %#", mystring);
NSMutableArray *myMutableArray = [json mutableCopy];
NSArray *myArray = [myMutableArray copy];
NSLog(#"json: %#", myArray);
self.greekLetters = #[#"test", #"test2"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myArray.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDictionary *cellDict = [myArray objectAtIndex:indexPath.row];
cell.textLabel.text = [cellDict objectForKey:#"address_line1"];
cell.detailTextLabel.text = [cellDict objectForKey:#"zipcode"];
return cell;
}
#end
Step-1
#interface ViewController ()
{
// create the array
NSMutableArray *myMutableArray;
}
#end
Step-2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSError *error;
NSString *url_string = [NSString stringWithFormat: #"http://django-env2.55jfup33kw.us-west-2.elasticbeanstalk.com/api/Musician/?format=json"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// allocate the memory of your array
myMutableArray = [NSMutableArray array];
// check your dictionary contains values or not
if (json)
{
// add the data to your array
[myMutableArray addObject:json];
[yourTableViewname reLoaddata]; // refresh the table
}
}
your JSON output is
step-3
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return myMutableArray.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDictionary *cellDict = [myMutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = [cellDict objectForKey:#"first_name"];
cell.detailTextLabel.text = [cellDict objectForKey:#"last_name"];
return cell;
}
pretty simple question.
How do i create two arrays from my NSDictionary full of Json data?
How do i then use these in my next vc and set that to the value of my cell.label.text?
Here is my current code as follows:
GroupsHomeViewController.h
// Toggle View Button (on button click open next view controller and populate table view with group matching data)
- (IBAction)ShowModels:(id)sender {
NSString *var1 = self.groupLabel.text.lowercaseString;
NSString *var3 = [var1 stringByReplacingOccurrencesOfString:#" " withString:#""]; //how to remove spaces personal reference.
NSString *var2 = self.groupLabel.text.lowercaseString;
NSString *var4 = [var2 stringByReplacingOccurrencesOfString:#" " withString:#""];
NSURLSession *session = [NSURLSession sharedSession];
// NSLog(#"%#", var3); used for testing remove upon completion.
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.test.com/%#/%#.json", var3, var4]] completionHandler:^(
NSData *data,
NSURLResponse *response,
NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//need to assign #amount to a nsarray somehow and then display in next vc.
//need to also assign amake to an nsarray and send to next vc also.
NSLog(#"%#", json);
}];
//Run the completed task.
[dataTask resume];
}
ModelViewController.h
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Set number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Set number of rows.
return 0; //change to count.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
}
//cell.textLabel.text = #amount //...need to find code for this...
//cell.detailedLabel.text = #model
// Set data for cell:
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I would just like to know how to create the NSArray out of my dictionary i already know how to set them to my cell.label.text. Thanks for your help.
JSON format:
{
amount = 2;
make = V8;
}
Lee Sugden you can easily get the data from dictionary and you ca add the objects to array.
NSMutableArray *arrJsonAmount = [[NSMutableArray alloc]init];
NSMutableArray *arrJsonMake = [[NSMutableArray alloc]init];
[arrJsonAmount addObject:[json objectForKey:#"amount"]];
[arrJsonMake addObject:[json objectForKey:#"Make"]];
UITableView DataSource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrJsonAmount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
}
cell.textLabel.text = arrJsonAmount[indexPath.row];
cell.detailedLabel.text = arrJsonMake[indexPath.row];
return cell;
}
I am doing JSON parsing, but my data is only shown in log and not in Tableview.
I am showing the main method of JSON parsing below. I would like to show the whole code but Stack Overflow doesn't allow me.
- (void)viewDidLoad
{
[super viewDidLoad];
[_CenterTableview setHidden:NO];
[_CenterTableview reloadData];
NSString *str=#"http://www.vallesoft.com/vlcc_api/getservicenames.php?centrename=";
NSURL * url=[NSURL URLWithString:str];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:url];
Connection1=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if (Connection1) {
WebData1=[[NSMutableData alloc]init];
}
// [self.CenterTableview reloadData];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *json=[NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info =[json objectForKey:#"city_info"];
for(NSDictionary *dic in city_info)
{
NSArray *vlcc_service_name=[dic objectForKey:#"vlcc_service_name"];
Centers=[[NSMutableArray alloc]initWithObjects:vlcc_service_name, nil];
//This Nslog showing service name //
NSLog(#"%#",vlcc_service_name);
}
}
But in Tableview, it is not showing:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [Centers objectAtIndex:indexPath.row];
return cell;
}
You need to reload the tableview once you get the centers array filled in didFinishLoading
///Your code......
Centers=[[NSMutableArray alloc]initWithObjects:vlcc_service_name, nil];
[_CenterTableview reloadData];
////Your code.....
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