JSON to UITableView IOS Objective-C [closed] - ios

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;
}

Related

Preparing NSArray from NSdictionary to show in next VC

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;
}

Data not showing in table view in JSON parsing in iOS

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

tableView unable to display data parsed from the web in json format

I created an api using kimono and here is my code.
#import "PlayerRankingsTableViewController.h"
#import "RankingsTableViewCell.h"
#define kBgQueue dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kPlayerRankingsURL [NSURL URLWithString:#"https://www.kimonolabs.com/api/bg6tcuuq?apikey=xgp4nU6xA9UcBWSe0MIHcBVbAWz5v4wR"]
#interface PlayerRankingsTableViewController () {
}
#property (nonatomic, strong) NSArray *playerRankings;
#end
#implementation PlayerRankingsTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:
kPlayerRankingsURL];
[self performSelectorOnMainThread: #selector(initializePlayerRankingsArray:)
withObject:data waitUntilDone:YES];
});
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be rexrcreated.
}
- (NSArray *)initializePlayerRankingsArray:(NSData *)responseData {
NSError* error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray *myPlayerRankings = [[json objectForKey:#"results"]objectForKey:#"collection1"];
self.playerRankings = myPlayerRankings;
NSLog(#"%#", self.playerRankings);
return self.playerRankings;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.playerRankings count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RankingsTableViewCell *cell = (RankingsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = (RankingsTableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
NSDictionary *rankings = [self.playerRankings objectAtIndex: indexPath.row];
NSString *rank = [rankings objectForKey:#"rank"];
NSString *name = [rankings objectForKey:#"name"];
NSString *points = [rankings objectForKey:#"points"];
[cell.playerRank setText:rank];
cell.playerName.text = name;
cell.playerPoints.text = points;
return cell;
}
#end
I think there is nothing wrong with data parsing process, because the console displays my data parsed from the web correctly.
However, when I ran the app, I saw nothing but a empty table.
Again, I think this might be something simple and new to programming.
Thank you in advance, and sorry for being such a burden.
In initializePlayerRankingsArray: you shouldn't be returning the array because nothing it there to receive it. You have already set self.playerRankings, so that is enough.
What is missing from this method is [self.tableView reloadData]; (which should be the last line after self.playerRankings is set).

How to send value to anthor Page from table view iOS [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 8 years ago.
I have done for parsing data from JSON and put it show in Table view.
So I want to pass data (catID and catName )to another Page it's DetailPageController
how can I do like that? the below is my code.
Thanks in advance!
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *myObject;
// A dictionary object
NSDictionary *dictionary;
// Define keys
NSString *catName;
NSString *catID;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
catName =#"Category Name";
catID=#"Category ID";
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"MY_URL"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *TheCatName = [dataDict objectForKey:#"cat_name"];
NSString *TheCatID = [dataDict objectForKey:#"cat_id"];
NSLog(#"cat_name: %#",TheCatName);
NSLog(#"cat_id: %#",TheCatID);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
TheCatName, catName,
TheCatID, catID,
nil];
[myObject addObject:dictionary];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return myObject.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Item";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[[UITableViewCell alloc]initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *textcat;
textcat = [NSMutableString stringWithFormat:#"%#",
[tmpDict objectForKeyedSubscript:catName]];
NSMutableString *catid;
catid = [NSMutableString stringWithFormat:#"ID: %# ",
[tmpDict objectForKey:catID]];
cell.textLabel.text = textcat;
cell.detailTextLabel.text= catid;
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *catID;
catID = [NSMutableString stringWithFormat:#"%#",
[tmpDict objectForKeyedSubscript:cat_id]];
NSLog(#"didSelectRowAtIndexPath");
/*UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:#"You've selected a row" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];*/
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:catID delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display the Hello World Message
[messageAlert show];
// Checked the selected row
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
First import DetailPageController in TableviewController Class with help of following line.
#import "DetailPageController.h"
Now implement following method in your TableViewController Class
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailPageController * detailPageControllerOBJ_ = [[ImageOptionViewController alloc]initWithNibName:#“XIBName bundle:nil];
detailPageControllerOBJ_.dicSelectedData = [self.arrayData objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailPageControllerOBJ_ animated:YES];
}
And in DetailPageController.h put following code.
#property (nonatomic,strong) NSDictionary * dicSelectedData;
You will get your selected data in dicSelectedData Dictionary

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;
}

Resources