How to show json data in table view in xcode - ios

i am new to ios and am currently working in json. I am just using itunes top 10 albums which to be displayed in table view i received data i formatted and displayed in table view but i can able to display only album name but i want to display all details of particular album which is to be displayed in same cell.
Here is my full code
- (void)viewDidLoad
{
[super viewDidLoad];
albumtop=[[NSMutableArray alloc]init];
[[self itunestTable]setDataSource:self];
[[self itunestTable]setDelegate:self];
NSURL *url=[NSURL URLWithString:#"https://itunes.apple.com/in/rss/topalbums/limit=10/json"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
albumdata =[[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[albumdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[albumdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"error in connection");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *alldata =[NSJSONSerialization JSONObjectWithData:albumdata options:0 error:nil];
NSDictionary *album =[alldata objectForKey:#"feed"];
NSArray *total =[album objectForKey:#"entry"];
for(NSDictionary *top in total)
{
NSDictionary *albumname =[top objectForKey:#"im:artist" ];
title =[albumname objectForKey:#"label"];
[albumtop addObject:title];
}
[[self itunestTable]reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [albumtop count];
}
-(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];
}
cell.textLabel.text=[albumtop objectAtIndex:indexPath.row];
return cell;
}
Program working well
My output will be like this
---------------------------------
Jones
---------------------------------------
carry Kim
---------------------------------------
i can able to fetch single value only how can i display all the details of the album like this
----------------------------------
Jones
no.tracks 10
price 180
---------------------------------------
carry Kim
no.tracks 10
price 180
---------------------------------------
how i can achieve this help me.. thanks in advance

You need to add Thee label in your UITableViewCell.
And fetch each Value as you needed. It is simple fetch as you fetch value of name and put it to relevant UILabel.
You also need to expand size of your cell of UITableView by following method.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
return 80;// write as you need.
}

you have to use costum UITableviewCells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BDCustomCell"];
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"BDCustomCell" owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = [topLevelObjects objectAtIndex:0];
}
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.....

Two tableView in One Controller

Want to use two tableView in one viewController but it give me error like:
this class is not key value coding-compliant for the key tableView.
I have two tableView 1.)tableViewTwo and 2.)tableViewThree but not wokring.
but when i used the name tableView then data shows on the first tableView.
and how can i use the different custom cell on both tableView. (CustomerListCell for (First TableView) and CustomerListCellThree for (Second TableView)
Can anyone please suggest me the best way to do this. I have search a lot and trying many suggestion which i found on internet and stackoverflow.
Thanks In Advanced.
- (void)viewDidLoad
{
NSURLRequest *requestTwo=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://xyzt.com?key=init"]];
responseData=[[NSMutableData alloc]init];
urlConnection=[[NSURLConnection alloc]initWithRequest:requestTwo delegate:self];
NSURLRequest *requestThree=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://xyzt.com?key=init"]];
responseDataThree=[[NSMutableData alloc]init];
urlConnectionThree=[[NSURLConnection alloc]initWithRequest:requestThree delegate:self];
}
#pragma mark - Connection Details
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
if (connection == urlConnection) {
NSLog(#"Error");
}
else if (connection == urlConnectionThree){
NSLog(#"Error");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if (connection == urlConnection) {
[responseData setLength:0];
}
else if (connection == urlConnectionThree){
[responseDataThree setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if (connection == urlConnection) {
[responseData appendData:data];
}
else if (connection == urlConnectionThree) {
[responseDataThree appendData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == urlConnection) {
NSError *error=nil;
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
self.totalData=[dic objectForKey:#"data"];
totalTitle=[[NSMutableArray alloc]init];
totalImage=[[NSMutableArray alloc]init];
totalIdWorks=[[NSMutableArray alloc]init];
[_tableViewTwo reloadData];
}
else if (connection == urlConnectionThree){
NSError *error=nil;
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseDataThree options:NSJSONReadingMutableContainers error:&error];
self.totalDataThree=[dic objectForKey:#"data"];
totalTitleThree=[[NSMutableArray alloc]init];
totalImageThree=[[NSMutableArray alloc]init];
totalIdWorksThree=[[NSMutableArray alloc]init];
[_tableViewThree reloadData];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableViewTwo) {
return [totalData count];
}
else if (tableView == self.tableViewThree){
return [totalDataThree count];
}
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"CustomerListCell";
CustomerListCell *cell = (CustomerListCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomerListCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
return cell;
}
Try this.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40.0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == tableViewFirst)
return arrfirst.count;
else if(tableView==tableViewSecond)
return arrsecond.count;
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == tableViewfirst)
{
// First tableViewcell
return cell;
}
else if (tableView == tableViewsecond)
{
//Second tableViewCell
return cell;
}
return nil;
}
No matter how much table view you have in a single viewController. As you said you have two tableView tableViewTwo & tableViewThree. So you have to create two array for two datasource. Then set the delegate of both table view.
[tableViewTwo setDelegate:self];
[tableViewThree setDelegate:self];
Now when you reload your table views
[tableViewTwo reloadData];
[tableViewThree reloadData];
for both table view the same delegate will called one after another. As you already put the condition on
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
do the same thing for all the delegate method you have implemented and you want to make differ for different table view. One thing I want to include use ([tableView isEqual:self.tableViewTwo]) instead (tableView == self.tableViewTwo)
i think this is helpful you for understand #Tapas Pal said set delegates for both tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *customCell;
UITableViewCell *customTabelCell;
if(tableView == self.tableViewTwo){
customCell=#"CustomerListCellTwo";
customTabelCell=CustomerListTabelCellTwo;
}else{
customCell=#"CustomerListCellThree";
customTabelCell=CustomerListTabelCellThree;
}
static NSString *simpleTableIdentifier = customCell;
customTabelCell *cell = (customTabelCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:customCell owner:self options:nil];
cell = [nib objectAtIndex:0];
}
return cell;
}

iOS Basic Request to webservice

Can anyone point me in the right direction of a good tutorial or possibly answer this question.
I have some JSON to be returned on my web server
{
first_name: "Joe";
last_name: "Smith";
department: "Human Resources";
}
How do I make a http request to get this information at the click of a button and display as text on the iphone.?
Complete newbie so please 'dumb' down.
create a jsonviewcontroller class
#import <UIKit/UIKit.h>
#interface JSONViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>
{
NSString *label;
}
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
- (IBAction)getTop10AlbumAction:(id)sender;
#end
then in implementation class:-
#import "JSONViewController.h"
#interface JSONViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSString *category;
}
#end
#implementation JSONViewController
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Failed with Error");
}
this is the place where actual parsing happens, we fetch the title of albums from respective dictionary and arrays. to understand this first go to this link http://jsonviewer.stack.hu/#http://itunes.apple.com/us/rss/topalbums/limit=10/json this is the json viewer which shows the structure of the content that we are going to access. dont panic! its really easy if u try parsing some json urls
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"];
NSArray *arrayOfEntry=[feed objectForKey:#"entry"];
for (NSDictionary *dict in arrayOfEntry) {
NSDictionary *title=[dict objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self myTableView]reloadData];
}
- (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[array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//clear background color
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
//set cell text
cell.textLabel.text=[array objectAtIndex:indexPath.row];
//set cell accessory type
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
here we specify the itunes url that we are going to parse and make connection request
- (IBAction)getTop10AlbumAction:(id)sender {
NSURL *url=[NSURL URLWithString:#"http://itunes.apple.com/us/rss/topalbums/limit=10/json"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData=[[NSMutableData alloc]init];
}
[[self myTableView]reloadData];
}
#end
i hope i have made it clear enough!
I suggest you two different tutorials:
Creating a simple interface. Here is a sample from Apple that have a button and a text displayed: iOS Button - Label sample
Insert into controller code (i.e. changeGreeting:) the code that calls the webservice: iOS JSON Webservice tutorial

nsurl to uimageview does not show after parsing json array

Well in my .m file I am doing the following:
I am fetching data over the web and store them in an NSMutable array by parsing json array. These data are images urls (images are on my server) and then I want to set them on my custom cell. each cell has 2 imageviews.
I am parsing the data correctly.
i do store them correctly.
I can see their values printed out and If i open them in a browser they are correct values.
If in my cell place static images from my resources I can see them.
But If i try to set them from the url I do not see anything.
here is my code:
For fetching data:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&myError];
images_url= [NSMutableArray new];
for (NSDictionary *alert in json ){
NSString* image = [alert objectForKey:#"image"];
[images_url addObject:image];
}
[self.myTable reloadData];
}
where myTable is my synthesized TableView.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int i=[images_url count]/2;
return i;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier=#"ListTableCell";
//this is the identifier of the custom cell
ListsCell *cell = (ListsCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ListsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
/*NSString *url_left=[images_url objectAtIndex:(indexPath.row*2)];
NSLog(#"Left url is:%#",url_left);
NSString *url_right=[images_url objectAtIndex:(indexPath.row*2+1)];
NSLog(#"Right url is:%#",url_right);*/ THEY ARE PRINTED HERE
NSURL *url_left=[NSURL URLWithString:[images_url objectAtIndex:(indexPath.row*2)]];
cell.Left.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url_left]];
NSURL *url_right=[NSURL URLWithString:[images_url objectAtIndex:(indexPath.row*2+1)]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 81;
}
If I remove the reload data, then I do bot see their values and not the correct number of lines, so it is necessary.
So can anyone find out what is wrong in here?

Resources