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;
}
Related
I hope you guys help me in my code which is load data from a website. Let's start with the code:
-(void)viewDidLoad
{
[self loadDataFromUrl];
}
-(void)loadDataFromUrl {
NSString *myUrl = [NSString stringWithFormat:#"http://WebSite/PhpFiles/File.php"];
NSURL *blogURL = [NSURL URLWithString:myUrl];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
for (NSDictionary *bpDictionary in dataDictionary) {
HotelObject *currenHotel = [[HotelObject alloc]initWithVTheIndex:
[bpDictionary objectForKey:#"TheIndex"] timeLineVideoUserName:
[bpDictionary objectForKey:#"timeLineVideoUserName"] timeLineVideoDetails:
[bpDictionary objectForKey:#"timeLineVideoDetails"] timeLineVideoDate:
[bpDictionary objectForKey:#"timeLineVideoDate"] timeLineVideoTime:
[bpDictionary objectForKey:#"timeLineVideoTime"] timeLineVideoLink:
[bpDictionary objectForKey:#"timeLineVideoLink"] timeLineVideoLikes:
[bpDictionary objectForKey:#"timeLineVideoLikes"] videoImage:
[bpDictionary objectForKey:#"videoImage"] timeDeviceToken:
[bpDictionary objectForKey:#"deviceToken"]];
[self.objectHolderArray addObject:currenHotel];
}
}
-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
HotelObject *currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.row];
cell.lblID.text = currentHotel.vvTheIndex;
cell.lblName.text = currentHotel.vvUserName;
cell.lblCity.text = currentHotel.vvVideoDate;
cell.lblAddress.text = currentHotel.vvVideoLikes;
return cell;
}
The above code is loading data from a Url and fill the TableView and this step working fine. The app has another ViewController which is DetailsView, in DetailsView users can update some info. When the user goes back to the TableView nothing happened (I mean the data still the same and not updated). I have tried to call the loadDataFromurl from ViewDidAppear but it does not work.
I did add:
[self.tableView reloadData];
But still the same result.
Her is also my NSObject code:
-(instancetype)initWithVTheIndex:(NSString *)vTheIndex
timeLineVideoUserName:(NSString *)vUserName
timeLineVideoDetails:(NSString *)vVideoDetails
timeLineVideoDate:(NSString *)vVideoDate
timeLineVideoTime:(NSString *)vVideoTime
timeLineVideoLink:(NSString *)vVideoLink
timeLineVideoLikes:(NSString *)vVideoLikes
videoImage:(NSString *)vVideoImage
timeDeviceToken:(NSString *)vDeviceToken {
self = [super init];
if(self){
self.vvTheIndex = vTheIndex;
self.vvUserName = vUserName;
self.vvVideoDetails = vVideoDetails;
self.vvVideoDate = vVideoDate;
self.vvVideoTime = vVideoTime;
self.vvVideoLink = vVideoLink;
self.vvVideoLikes = vVideoLikes;
self.vvVideoImage = vVideoImage;
self.vvDeviceToken = vDeviceToken;
}
return self;
}
My question is: How can I update the TableView when moving from DetailsView or even when I pull to refresh.
Thanks in advance
You are not properly reloading the data source of your UITableView.
Assuming the remote URL is getting updated with the new data, and the issue is only reloading the TableView, make sure you add your [self.tableView reloadData] AFTER loadDataFromUrl has finished.
The reloadData method will always refresh the table's content, so either it's not being called at the right time or you are not updating self.objectHolderArray. (You can debug that by setting a breakpoint after calling loadDataFromUrl after the update.)
on viewDidLoad lifecycle first [self.tableView reloadData] reload tableview then another work.
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;
}
I'm trying to parse a json-file containing links to images. This is my code:
#import "Pictures.h"
#import "DEMONavigationController.h"
#import "PicturesObject.h"
#interface Pictures ()
{
NSInteger refreshIndex;
NSArray *images;
NSMutableArray *jsonIs;
NSArray *items;
IBOutlet UIImageView *imagesinsta;
}
#end
#implementation Pictures
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Pictures";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu"
style:UIBarButtonItemStylePlain
target:(DEMONavigationController *)self.navigationController
action:#selector(showMenu)];
// ***************** FETCHING DATA ******************* //
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"link-to-json.php?image=Image"]];
NSData *data= [NSData dataWithContentsOfURL:URL];
if (data == nil) {
return;
}
NSError* error;
items = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"Json : %#",jsonIs);
if (jsonIs != nil) {
NSMutableDictionary* aDict = jsonIs[0];
NSString *item_media = [aDict objectForKey:#"link"];
}
// ***************** FETCHING DATA ******************* //
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"PicturesObject";
PicturesObject *cell = (PicturesObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PicturesObject" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *item = [items objectAtIndex:indexPath.row];
NSString *item_media = [item objectForKey:#"link"];
return cell;
}
- (void)issueLoadRequest
{
// Dispatch this block asynchronosly. The block gets JSON data from the specified URL and performs the proper selector when done.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"link-to-json.php?image=Image"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
- (void)receiveData:(NSData *)data {
// When we have the data, we serialize it into native cocoa objects. (The outermost element from twitter is
// going to be an array. I JUST KNOW THIS. Reload the tableview once we have the data.
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tweets.count;
}
#end
This is how my custom PicturesObject table view look like:
But when I launch my app I only get a screen like this:
Json Data is similar to Dictionary and not an array. Instead of using
NSArray items
use
NSDictionary items
and then extract the the relevant data from dictionary.
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
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?