nsurl to uimageview does not show after parsing json array - ios

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?

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

display json datas table view in segmented control

friends,
i need to display list of details as in image in a table view datas from json service I tried the below code but it doesnot work out
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"unrealized";
samplecell *cell = (samplecell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"unrealized" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
else if(mySegmentedcontrol.selectedSegmentIndex==3)
{
settings.hidden=YES;
connection.hidden=YES;
openTrades.hidden=YES;
closedTrades.hidden=NO;
NSString *link=[NSString stringWithFormat:#"http://www.dummydata.com/MMWS/Client/ClosedTrades.ashx?ClientId=%#",clientId];
NSURL *URLGet=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:URLGet];
NSError *error;
jsonReturnArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"json%#",jsonReturnArray);
cell.unRealizedProfit.text=[[jsonReturnArray valueForKey:#"Profit"]objectAtIndex:0];
cell.strategy.text=[[jsonReturnArray valueForKey:#"StrategyName"]objectAtIndex:0];
NSString *totalProfit=[[jsonReturnArray valueForKey:#"TotalProfit"]objectAtIndex:0];
closedTotalUnrealizedProfit.text=totalProfit;
}
NSString *cellValue = [jsonReturnArray objectAtIndex:indexPath.row];
cell.unRealizedProfit.text=cellValue;
cell.unRealizedProfit.text = [jsonReturnArray valueForKey:#"Profit"];
cell.strategy.text =[jsonReturnArray valueForKey:#"StrategyName"];
return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"json%#",jsonReturnArray);
return jsonReturnArray.count;
}
I also tried the code and donot know how to bring tableview property in seegmented control
else if(mySegmentedcontrol.selectedSegmentIndex==3)
{
settings.hidden=YES;
connection.hidden=YES;
openTrades.hidden=YES;
closedTrades.hidden=NO;
strategyClosed.hidden=NO;
NSString *link=[NSString stringWithFormat:#"http://www.dummmydata.com/MMWS/Client/ClosedTrades.ashx?ClientId=%#",clientId];
NSURL *URLGet=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:URLGet];
NSError *error;
jsonReturnArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"json%#",jsonReturnArray);
}
OK,
Your data source should not be get within the function cellForRowAtIndexPath, CellForRowAtIndexPath is for showing each cell of the row based on the tableView's dataSource. And apparently you should not get the datasource when each of the cell is rendering.
You should always make sure your tableView's dataSource is ready before you call [myTableView reloadData];
Solutions: in your viewDidAppear function block, write your logic as below
if(mySegmentedcontrol.selectedSegmentIndex==3){
NSString *link=[NSString stringWithFormat:#"http://www.dummydata.com/MMWS/Client/ClosedTrades.ashx?ClientId=%#",clientId];
NSURL *URLGet=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:URLGet];
NSError *error;
self.jsonDataSource = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
[self.thisTableView reloadData];
}
And then in your CellForRowAtIndexPath, do the normal thing like below
NSDictionary *objCellData = [self.jsonDataSource objectAtIndex:indexPath.row];
cell.cellData = objCellData;
return cell;
And then , in your Cell class, make sure you draw the title label, or value lable correctly by using the cellData it is assigned.
Please read the UITableView documentation before you code.
The UITableView rendering sequence is
DataSource is ready
Call [tableView reloadData];
UITableView dataSource/delegate functions will be fired, like numberOfRowsInSection, heightForRowAtIndexPath, cellForRowAtIndexPath, etc.
finally i got the answer i customized the cell and used below code for assigning number of rows depending on counts of array
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return jsonReturnArray.count;
}
then i displayed in table view using below code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"samplecell";
samplecell *cell = (samplecell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
//loads two table view for open and closed trades with reference of client id
if (cell == nil)
{
//table view for closed trades
if (tableView==strategyClosed)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"samplecell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSString *link=[NSString stringWithFormat:#"http://www.managedtradingsystems.com/MMWS/Client/ClosedTrades.ashx?ClientId=%#",clientId];
NSURL *URLGet=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:URLGet];
NSError *error;
jsonReturnArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//checks whether datas are present in array or array and datas present are null and displays datas present through labels
if (![jsonReturnArray isEqual:[NSNull null]])
{
NSString *strategy=[[jsonReturnArray valueForKey:#"StrategyName"]objectAtIndex:indexPath.row];
if (![strategy isEqual:[NSNull null]])
{
cell.strategy.text=strategy;
}
else
{
cell.strategy.text=#"";
}
the number of rows by below code using array count
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return jsonReturnArray.count;
}

How to show json data in table view in xcode

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

iOS - Unable to scroll UITableView after remote content loaded

When I load remote content via a block I update the UITableView by calling reloadData. However, I am unable to scroll on this data. I think this is because I have declared that the number of rows in the table is the length of my NSArray variable that will hold the contents of the list. When this is called though, the list has a count of zero. I would have assumed that by calling reloadData on the tableView that it would have recalculated the list size again.
Perhaps I'm missing a step along the way.
Thanks
Here is my code
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"MYURL"]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
-(void) fetchedData:(NSData *)responseData
{
NSError* error;
id json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
self.dataList = json;
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self.tableView reloadData];
});
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dataList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SongCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if([self.dataList count] > 0){
NSDictionary *chartItem = [self.dataList objectAtIndex:indexPath.row];
NSDictionary *song = [chartItem objectForKey:#"song"];
cell.textLabel.text = [song objectForKey:#"title"];
}
return cell;
}
Check that your json object (and therefore self.dataList) is not nil at the end of the asynchronous call. If it is, then [self.dataList count] will return 0.
Also, make sure that you correctly set self.dataList.dataSource.
This is working now.
The cause of the problem was the I had added a pan gesture to the UITableView
[self.view addGestureRecognizer:self.slidingViewController.panGesture];
This seems to interfere with the ability to scroll on a table. Hopefully this will help anyone who comes across this in the future.

Resources