I have a pull to refresh setup. It's currently calling [self.tableView reloadData]; but It's not reloading my parsed Json data from the blogData method. Is theres something I'm missing?
My controller is like this:
//
// ARTableViewController.m
// WorldCupLive
//
// Created by Adam Rais on 14/06/2014.
// Copyright (c) 2014 Adam Rais. All rights reserved.
//
#import "ARTableViewController.h"
#import "ARModal.h"
#interface ARTableViewController ()
#end
#implementation ARTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.blogPost = [[ARModal alloc] init];
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
[self randomBackgroundImage];
self.tableView.contentInset = UIEdgeInsetsMake(0.0f, -10.0f, 0.0f, 0.0f);
// Initialize Refresh Control
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
// Configure Refresh Control
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
// Configure View Controller
[self setRefreshControl:refreshControl];
}
-(void)randomBackgroundImage {
UIImage *image = self.blogPost.imageUI;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
self.tableView.backgroundView = imageView;
self.tableView.backgroundView.layer.zPosition -= 1;
}
- (void)refresh:(id)sender
{
NSLog(#"Refreshing");
[self.tableView reloadData];
[self randomBackgroundImage];
// End Refreshing
[(UIRefreshControl *)sender endRefreshing];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.blogPost.jsonMutable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// Configure the cell...
ARModal *post = [self.blogPost.jsonMutable objectAtIndex:indexPath.row];
NSData *imageData = [NSData dataWithContentsOfURL:post.jsonURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.textLabel.text = [[[[[post.home stringByAppendingString:#" "]stringByAppendingString:#" "] stringByAppendingString:post.bst] stringByAppendingString:#" "] stringByAppendingString:post.away];
cell.detailTextLabel.text = post.info;
cell.imageView.image = image;
cell.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.000];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
And my modal:
//
// ARModal.m
// WorldCupLive
//
// Created by Adam Rais on 14/06/2014.
// Copyright (c) 2014 Adam Rais. All rights reserved.
//
#import "ARModal.h"
#implementation ARModal
-(id)initWithHome:(NSString *)home {
self = [super init];
if (self) {
_home = home;
_away = nil;
_result = nil;
_info = nil;
_homeImage = nil;
}
return self;
}
+(id)blogPostWithHome:(NSString *)home {
return [[self alloc] initWithHome:home];
}
-(NSArray *)blogData {
NSURL *jsonURL = [NSURL URLWithString:#"http://www.kimonolabs.com/api/2nfgfo2s?apikey=1a1f5f323969d5157af8a8be857026c2"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *jsonError = nil;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];
NSArray *jsonArray = [[jsonDictionary objectForKey:#"results"] objectForKey:#"collection1"];
if (blogData == nil) {
blogData = jsonArray;
}
return blogData;
}
-(NSURL *)jsonURL {
return [NSURL URLWithString:self.homeImage];
}
-(NSString *)bst {
NSString *sentence = self.result;
NSString *word = #"-";
NSString *wordTwo = #"00.00";
NSString *wordThree = #"01.00";
NSMutableArray *bstArray = [NSMutableArray array];
if ([sentence rangeOfString:word].location != NSNotFound) {
NSLog(#"Found the string");
[bstArray addObject:sentence];
} else if ([sentence rangeOfString:wordTwo].location != NSNotFound) {
NSLog(#"time is 23:00");
[bstArray addObject:#"23:00"];
} else if ([sentence rangeOfString:wordThree].location != NSNotFound) {
NSLog(#"time is 00:00");
[bstArray addObject:#"00:00"];
} else {
float floatOne = [sentence floatValue];
float floatFinal = floatOne - 1.000000;
NSString *str = [NSString stringWithFormat:#"%f", floatFinal];
NSString *bstFinal = [str substringToIndex:[str length] - 4];
[bstArray addObject:bstFinal];
}
return [bstArray objectAtIndex:0];
}
-(UIImage *)imageUI {
NSArray *imageArray = #[[UIImage imageNamed:#"Algeria"],[UIImage imageNamed:#"Argentina"],[UIImage imageNamed:#"Australia"],[UIImage imageNamed:#"Belgium"],[UIImage imageNamed:#"Bosnia-Herzegovina"],[UIImage imageNamed:#"Switzerland"],[UIImage imageNamed:#"Uruguay"],[UIImage imageNamed:#"USA"],[UIImage imageNamed:#"Brazil"],[UIImage imageNamed:#"Cameroon"],[UIImage imageNamed:#"Chile"],[UIImage imageNamed:#"Colombia"],[UIImage imageNamed:#"Costa Rica"],[UIImage imageNamed:#"Côte d'Ivoire"],[UIImage imageNamed:#"Croatia"],[UIImage imageNamed:#"Ecuador"],[UIImage imageNamed:#"England"],[UIImage imageNamed:#"France"],[UIImage imageNamed:#"Germany"],[UIImage imageNamed:#"Ghana"],[UIImage imageNamed:#"Greece"],[UIImage imageNamed:#"Honduras"],[UIImage imageNamed:#"Iran"],[UIImage imageNamed:#"Italy"],[UIImage imageNamed:#"Japan"],[UIImage imageNamed:#"Mexico"],[UIImage imageNamed:#"Netherlands"],[UIImage imageNamed:#"Nigeria"],[UIImage imageNamed:#"Portugal"],[UIImage imageNamed:#"Russia"],[UIImage imageNamed:#"South Korea"],[UIImage imageNamed:#"Spain"]];
int random = arc4random_uniform(imageArray.count);
return [imageArray objectAtIndex:random];
}
#end
When you call the -[UITableView reloadData] method you are telling the tableview to refresh ints content based on the source you already gave him, but he doesnt change the source. In some cases you refresh you datasource and you need to refresh the UITableView so you call the -[UITableView reloadData]. What you need to do is to first refresh you data and the refresh the view, so the view uses your new data.
Use the the same way you got the data from your modal to refresh it.
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
Then execute the -[UITableView reloadData], but now he is going to refresh using the refreshed data that you got from your modal.
If you need something else, comment.
-[UITableView reloadData] doesn't actually reload your data. It tells the table that you've reloaded the data, and now you need the table view to reload.
So before you call reloadData you should do:
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
Also as this chunk of code only uses information provided by ARModal, you should probably put it in a method in ARModal
Related
Hi My data is getting duplicated every time I use the pull to refresh.. for eg. 5 initial entries in the table view are doubled to 10 with one pull to refresh and adding 5 more in the subsequent pull to refresh. How can I stop the duplication.. I would like to make sure that only new items are downloaded and existing data in the table is not downloaded again.
#implementation RootViewController
#synthesize allEntries = _allEntries;
#synthesize feeds = _feeds;
#synthesize queue = _queue;
#synthesize webViewController = _webViewController;
#pragma mark -
#pragma mark View lifecycle
- (void)addRows {
RSSEntry *entry1 = [[[RSSEntry alloc] initWithBlogTitle:#"1"
articleTitle:#"1"
articleUrl:#"1"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry2 = [[[RSSEntry alloc] initWithBlogTitle:#"2"
articleTitle:#"2"
articleUrl:#"2"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry3 = [[[RSSEntry alloc] initWithBlogTitle:#"3"
articleTitle:#"3"
articleUrl:#"3"
articleDate:[NSDate date]] autorelease];
[_allEntries insertObject:entry1 atIndex:0];
[_allEntries insertObject:entry2 atIndex:0];
[_allEntries insertObject:entry3 atIndex:0];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Songs";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:
#"http://hindisongs.bestofindia.co/?feed=rss2",
nil];
self.refreshControl = [UIRefreshControl new];
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to refresh"];
[self.refreshControl addTarget:self action:#selector(bindDatas) forControlEvents:UIControlEventValueChanged];
[self bindDatas]; //called at the first time
}
-(void)bindDatas
{
//GET YOUR DATAS HERE…
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
//update the tableView
[self.tableView reloadData];
if(self.refreshControl != nil && self.refreshControl.isRefreshing == TRUE)
{
[self.refreshControl endRefreshing];
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseAtom:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSString *blogTitle = [rootElement valueForChild:#"title"];
NSArray *items = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = nil;
NSArray *links = [item elementsForName:#"link"];
for(GDataXMLElement *link in links) {
NSString *rel = [[link attributeForName:#"rel"] stringValue];
NSString *type = [[link attributeForName:#"type"] stringValue];
if ([rel compare:#"alternate"] == NSOrderedSame &&
[type compare:#"text/html"] == NSOrderedSame) {
articleUrl = [[link attributeForName:#"href"] stringValue];
}
}
NSString *articleDateString = [item valueForChild:#"updated"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC3339];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries 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:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - %#", articleDateString, entry.blogTitle];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController.entry = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
self.webViewController = nil;
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[_allEntries release];
_allEntries = nil;
[_queue release];
_queue = nil;
[_feeds release];
_feeds = nil;
[_webViewController release];
_webViewController = nil;
[super dealloc];
}
The issue is that you keep inserting object to _allEntries without ever reseting it. You will want to empty it out at some point, either when the user pulls to refresh or when the new data comes in before you add any new objects to it.
[_allEntries removeAllObjects];
Try putting it at the start of bindDatas.
I am trying to to pretty standard operation, which is basically, getting all records form my local SQLITE database, then getting additional data form web, merge this data (which is NSMutableArray) and display it in table view. In viewDidLoad, array has all required elements, but in numberOfRowsInSection: it equals to nil. Because of this, I cannot display items in tableview. So where could it get set to nil? Thank you for any help.
Code for InboxViewControler.m
//
// ArticleViewController.m
// ReadLater
//
// Created by Ibragim Gapuraev on 09/06/2014.
// Copyright (c) 2014 Sermilion. All rights reserved.
//
#import "InboxViewController.h"
#import "LoginViewController.h"
#import "SHCTableViewCell.h"
#interface InboxViewController ()
#end
#implementation InboxViewController
#synthesize db, articles, response, jsonData;
- (NSMutableArray* ) articles
{
if (!articles) {
articles = [[NSMutableArray alloc] initWithCapacity:20];
}
return articles;
}
- (Database* ) db
{
if (!db) {
db = [[Database alloc] init];
}
return db;
}
//---------------------------------Getting data from web-------------------------------------------//
/**
The method will connect to a given url and send date of article that has been added at last.
Then, connectionDidFinishLoading will receive json array of all articles, that have been added to server database after that time
**/
#pragma mark Connection to server
- (void) makeConnetion:(id)data
{
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost/nextril/index.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//send id of article that was added last, to server,
//which will return json arrya of all articles with id greater then the one sent
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
if (connection) {
NSLog(#"viewWillAppear: Connecting to server to get data...");
}else{
NSLog(#"viewWillAppear: Error while connecting...");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
response = [[NSData alloc] initWithData:data];
}
//Check if data been received
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if(sizeof(response)>0){
//NSLog(#"Got response from server %#", response);
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:response //1
options:kNilOptions
error:&error];
self.jsonData = [[NSMutableArray alloc] initWithArray:json];
int count = 0;
[self.db openDatabase];
BOOL added = false;
BOOL addedToUser = false;
NSLog(#"jsonData %d", jsonData.count);
for (int i=0; i<self.jsonData.count; i++) {
NSDictionary *item = [self.jsonData objectAtIndex:i];
NSString* content = [item objectForKey:#"content"];
NSString* author = [item objectForKey:#"author"];
NSString* date = [item objectForKey:#"date"];
NSString* url = [item objectForKey:#"url"];
NSString* tags = [item objectForKey:#"tags"];
NSInteger archived = [[item objectForKey:#"archived"]integerValue];
NSString* title = [item objectForKey:#"title"];
//NSLog(#"",);
Article* article = [[Article alloc]initWithId:0 content:content author:author date:date url:url tags:tags arhived:archived title:title];
added = [self.db addArticleToArticleDB:article];
if (added == true) {
NSInteger last_id = [self.db getLastArticleID];
article.article_id = last_id;
[self.articles addObject:article];
addedToUser = [self.db addArticleToUserArticleDB:article];
}
count++;
}
if (added == true && addedToUser == true) {
NSLog(#"connectionDidFinishLoading: Articles has been imported. Size: %d %lu", jsonData.count, (unsigned long)jsonData.count);
}else{
NSLog(#"connectionDidFinishLoading: Failed to import article.");
}
NSArray *importedArticles = [self.db importAllArticlesForUser:16 archived:0];
[self.articles addObjectsFromArray:importedArticles];
[self.db closeDatabase];
}else{
NSLog(#"connectionDidFinishLoading: Did not get resopnse from server: %#", response);
}
connection = nil;
}
//----------------------------------------------------------------------------------------------------
#pragma mark TODO: work out why data from server loads only after second login
#pragma mark view
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.db openDatabase];
NSString* date_added = [self.db getLastArticleDate];
[self makeConnetion:(id)date_added];
NSLog(#"viewWillAppear: self.articles: %d", self.articles.count);
[self.db closeDatabase];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.separatorColor = [UIColor clearColor];
self.tableView.backgroundColor = [UIColor blackColor];
[self.tableView registerClass:[SHCTableViewCell class] forCellReuseIdentifier:#"Content"];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSLog(#"numberOfRowsInSection: self.articles: %d", self.articles.count);
return self.articles.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Content";
SHCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.backgroundColor = [UIColor clearColor];
NSMutableArray* safeArticles = self.articles;
// Configure the cell...
Article* article = [safeArticles objectAtIndex:indexPath.row];
NSString *listingKey = article.title;
NSString *listingValues = article.url;
cell.textLabel.text = listingKey;
cell.detailTextLabel.text = listingValues ;
cell.delegate = self;
cell.todoItem = article;
return cell;
}
#pragma mark cell atributes
-(UIColor*)colorForIndex:(NSInteger) index {
NSUInteger itemCount = self.articles.count - 1;
float val = ((float)index / (float)itemCount) * 0.6;
return [UIColor colorWithRed: 1.0 green:val blue: 0.0 alpha:1.0];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 70.0f;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [self colorForIndex:indexPath.row];
}
#pragma mark TODO delete from server database
//method to delete an article form view and to call method to delete from database, as well as form server database
-(void)deleteArticle:(Article*)articleToDelete {
. . .
}
#pragma mark TODO delete from server database
//method to delete an article form view and to call method to delete from database, as well as form server database
-(void)archiveArticle:(Article*)articleToArchive {
. . .
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
A tableView calls the datasource methods to populate itself just after viewDidLoad. If, at that point, the data source (which is usually an Array) is empty, nothing will appear in the tableView. That is why one has to call reloadData after the data source is brought into existence. This is especially needed in cases the data source is being fetched asyncronously.
According to Apple's documentation about reloadData:
Call this method to reload all the data that is used to construct the
table, including cells, section headers and footers, index arrays, and
so on. For efficiency, the table view redisplays only those rows that
are visible. It adjusts offsets if the table shrinks as a result of
the reload. The table view's delegate or data source calls this
method when it wants the table view to completely reload its data. It
should not be called in the methods that insert or delete rows,
especially within an animation block implemented with calls to
beginUpdates and endUpdates
Took advice of #akashg and added [self.tableView reloadData]; after fetching data. And it worked. Though, I don't know the mechanism of why this happened. At least it works ) Anyone welcome to add their explanation. Thank you.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Hey guys I am using Hpple to get some data from the web and display it in a table view. I am using the code from ray wenderlich. The source code is available at the bottom of this page http://www.raywenderlich.com/14172/how-to-parse-html-on-ios. Then this is the website I am using to get the data http://ueat.site88.net/output.xml. And here is my xPathQuery
//day[#name='monday']/meal[#name='LUNCH']/counter[#name='Entrée']/dish/name.
It gets the info if I NSLog what should go in the table view
Tutorial *thisTutorial = [_objects objectAtIndex:indexPath.row];
NSLog(#"%#", thisTutorial.title);
cell.textLabel.text = thisTutorial.title;
but then it doesn't appear in the table view, I know the nodes are not nil.
Heres the code for where it display the data
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "TFHpple.h"
#import "Tutorial.h"
#import "Contributor.h"
#interface MasterViewController () {
NSMutableArray *_objects;
NSMutableArray *_contributors;
}
#end
#implementation MasterViewController
#synthesize detailViewController = _detailViewController;
- (void)loadTutorials {
// 1
NSURL *tutorialsUrl = [NSURL URLWithString:#"http://ueat.site88.net/output.xml"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
// 2
TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];
// 3
NSString *tutorialsXpathQueryString = #"//day[#name='monday']/meal[#name='LUNCH']/counter[#name='Entrée']/dish/name";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
// 4
NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in tutorialsNodes) {
// 5
Tutorial *tutorial = [[Tutorial alloc] init];
[newTutorials addObject:tutorial];
// 6
tutorial.title = [[element firstChild] content];
NSLog(#"%#", tutorial.title);
// 7
tutorial.url = [element objectForKey:#"href"];
}
// 8
_objects = newTutorials;
[self.tableView reloadData];
}
/*
- (void)loadContributors {
// 1
NSURL *contributorsUrl = [NSURL URLWithString:#"http://www.raywenderlich.com/about"];
NSData *contributorsHtmlData = [NSData dataWithContentsOfURL:contributorsUrl];
// 2
TFHpple *contributorsParser = [TFHpple hppleWithHTMLData:contributorsHtmlData];
// 3
NSString *contributorsXpathQueryString = #"//ul[#class='team-members']/li";
NSArray *contributorsNodes = [contributorsParser searchWithXPathQuery:contributorsXpathQueryString];
// 4
NSMutableArray *newContributors = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in contributorsNodes) {
// 5
Contributor *contributor = [[Contributor alloc] init];
[newContributors addObject:contributor];
// 6
for (TFHppleElement *child in element.children) {
if ([child.tagName isEqualToString:#"img"]) {
// 7
#try {
contributor.imageUrl = [#"http://www.raywenderlich.com" stringByAppendingString:[child objectForKey:#"src"]];
}
#catch (NSException *e) {}
} else if ([child.tagName isEqualToString:#"h3"]) {
// 8
contributor.name = [[child firstChild] content];
}
}
}
// 9
_contributors = newContributors;
[self.tableView reloadData];
}
*/
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Master", #"Master");
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadTutorials];
// [self loadContributors];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - Table View
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
switch (section) {
case 0:
return #"Tutorials";
break;
case 1:
return #"Contributors";
break;
}
return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
switch (section) {
case 0:
return _objects.count;
break;
case 1:
return _contributors.count;
break;
}
return 0;
}
// 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:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (indexPath.section == 0) {
Tutorial *thisTutorial = [_objects objectAtIndex:indexPath.row];
NSLog(#"%#", thisTutorial.title);
cell.textLabel.text = thisTutorial.title;
cell.detailTextLabel.text = thisTutorial.url;
} else if (indexPath.section == 1) {
Contributor *thisContributor = [_contributors objectAtIndex:indexPath.row];
cell.textLabel.text = thisContributor.name;
}
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (!self.detailViewController) {
self.detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
}
NSDate *object = [_objects objectAtIndex:indexPath.row];
self.detailViewController.detailItem = object;
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
Thanks for your help in advance
Your problem is simply that your first element contains new line characters. If you strip these out -
tutorial.title = [[[element firstChild] content]stringByReplacingOccurrencesOfString:#"\n" withString:#""];
then the table rows display correctly.
I have a backend made in C#, where I am making WCF calls to from iOS. It works pretty good, but I am stuck in a problem
Code:
#import "ListTableViewController.h"
#import "ListServiceSvc.h"
#import "LoginViewController.h"
#interface ListTableViewController (){
NSMutableArray *productsFromWebServer;
NSMutableDictionary *prodForList;
}
#property (nonatomic, retain) NSMutableArray *shoppingList;
#property (nonatomic, retain) NSMutableArray *productList;
#end
#implementation ListTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
Boolean b = [standardUserDefaults boolForKey:#"HasTokenKey"];
if (!b)
{
[self showLoginViewController];
}
[self loadListsFromRemoteServer];
[self.tableView reloadData];
//self.uname.text = [standardUserDefaults objectForKey:#"username"];
}
- (void) showLoginViewController {
LoginViewController* loginController = (LoginViewController*) [ApplicationDelegate.storyBoard instantiateViewControllerWithIdentifier:#"LoginViewController"];
[self presentViewController:loginController animated:YES completion:nil];
}
- (void)userDidLeave
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setBool:NO forKey:#"HasTokenKey"];
// Show the Login screen.
[self showLoginViewController];
}
- (IBAction)exitAction
{
[self userDidLeave];
}
- (void)viewDidLoad
{
_shoppingList = [NSMutableArray array];
_productList = [NSMutableArray array];
//[self loadListsFromRemoteServer];
[super viewDidLoad];
}
-(void) loadListsFromRemoteServer
{
NSString *uname = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
NemListBinding *binding = [[ListServiceSvc NemListBinding]initWithAddress:#"http://balder/dm76_gr5/WCF.ListService.svc/custom?singleWsdl"];
binding.logXMLInOut=YES;
ListServiceSvc_GetShoppingListsWithUname *parms = [[ListServiceSvc_GetShoppingListsWithUname alloc]init];
parms.uname = uname;
[binding GetShoppingListsWithUnameAsyncUsingParameters:parms delegate:self];
}
-(void) loadItemsInList:(NSNumber*)slistId
{
NemListBinding *binding = [[ListServiceSvc NemListBinding]initWithAddress:#"http://balder/dm76_gr5/WCF.ListService.svc/custom?singleWsdl"];
binding.logXMLInOut=YES;
ListServiceSvc_GetProductsWithListId *parms = [[ListServiceSvc_GetProductsWithListId alloc]init];
parms.listId = slistId;
[binding GetProductsWithListIdAsyncUsingParameters:parms delegate:self];
}
- (void) operation:(NemListBindingOperation *)operation completedWithResponse:(NemListBindingResponse *)response
{
NSArray *responseHeaders = response.headers;
NSArray *responseBodyParts = response.bodyParts;
[NSThread sleepForTimeInterval:1.0];
NSMutableArray *shoppingListFromWebserver = [[NSMutableArray alloc] init];
productsFromWebServer = [[NSMutableArray alloc]init];
prodForList = [[NSMutableDictionary alloc]init];
// step 1 fill in the blanks.
for(id header in responseHeaders) {
// here do what you want with the headers, if there's anything of value in them
}
for (id mine in responseBodyParts)
{
if ([mine isKindOfClass:[ListServiceSvc_GetShoppingListsWithUnameResponse class]])
{
for (id slist in [[mine GetShoppingListsWithUnameResult] ShoppingList])
{
[shoppingListFromWebserver addObject:slist];
[self loadItemsInList:[slist ShoppingListId]];
//NSLog(#"new list :: RESPONSE FROM SERVER :: nList %#", [slist ShoppingListName]);
}
}
if ([mine isKindOfClass:[ListServiceSvc_GetProductsWithListIdResponse class]])
{
for (id products in [[mine GetProductsWithListIdResult] Product])
{
[prodForList setObject:[products ProductName] forKey:[products ShoppingListId]];
NSLog(#"new product :: RESPONSE FROM SERVER :: nList %#", [products ProductName]);
}
}
}
[self performSelectorOnMainThread:#selector(updateNewView:) withObject:shoppingListFromWebserver waitUntilDone:NO];
}
-(void) updateNewView:(NSMutableArray*) result
{
_shoppingList = result;
NSLog( #"new list - number of news :: %u", [_shoppingList count]);
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1; // the number of different sections in your table view
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_shoppingList count]; // the number of data in your shopping list
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ListCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
id shopList = [_shoppingList objectAtIndex:indexPath.row];
cell.textLabel.text = [shopList ShoppingListName];
NSNumber *sid = [shopList ShoppingListId];
//[self loadItemsInList:sid];
NSNumber *prodcount = [prodForList objectForKey:sid];
NSString* pcTostring = [NSString stringWithFormat:#"%#", prodcount];
cell.detailTextLabel.text = pcTostring;
return cell;
The log actually tells me that I am getting some products for the last List it gets. Problem is that all cell.detailText.text fields are null, until the last reload, then all cells disappear.
I am pretty sure I'm doing it wrong, but I cant get my head around hot to get the products for the selected list, when I need to get the ShoppingListId from the -(void) loadListsFromRemoteServer call in order to do the -(void) loadItemsInList:(NSNumber*)slistId
WCF connection was made with the help of wsdl2obj
C/xcode geeks!
I have been struggling with this error for hours now, and I don't seem to find the solution, although it seems as many people have had the exact same problem.
See code:
//
// ListViewController.m
// Puns
//
// Created by Amit Bijlani on 12/13/11.
// Copyright (c) 2011 Treehouse Island Inc. All rights reserved.
//
#import "ListViewController.h"
#import "BlogPost.h"
//#import "Pun.h"
#import "PunsTableViewCell.h"
#import "DetailViewController.h"
#implementation ListViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - Segue
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSLog(#"0");
if ( [[segue identifier] isEqualToString:#"ShowMenu"] ){
NSLog(#"1");
DetailViewController *dvc = (DetailViewController *)[segue destinationViewController];
dvc.menu = [self.blogPosts objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// GET WEB DATA SOURCE (JSON)
// The url
NSURL *blogURL = [NSURL URLWithString:#"http://constantsolutions.dk/json.html"];
// The data
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
// Error variable
NSError *error = nil;
// jsonData to serialization
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
// Get array 'posts'
self.blogPosts = [NSMutableArray array];
NSArray *blogPostsArray = [dataDictionary objectForKey:#"posts"];
for (NSDictionary *bpDictionary in blogPostsArray) {
// Get title
// Will only retrieve data, if TITLE exists
BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:#"title"]];
// Get the content
blogPost.content = [bpDictionary objectForKey:#"content"];
// Get thumbnail
blogPost.thumbnail = [bpDictionary objectForKey:#"thumbnail"];
// Get date
blogPost.date = [bpDictionary objectForKey:#"date"];
// Get price
blogPost.price = [bpDictionary objectForKey:#"price"];
// Add the object to blogPosts array
[self.blogPosts addObject:blogPost];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.blogPosts count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"PunTableViewCell";
PunsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[PunsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
BlogPost *blogPost = [self.blogPosts objectAtIndex:indexPath.row];
cell.menuTitle.text = blogPost.title;
cell.menuContent.text = blogPost.content;
if([blogPost.price length] == 0) {
[cell.menuPrice setHidden:YES];
} else {
cell.menuPrice.text = blogPost.price;
}
return cell;
}
#end
As you can see, I have implented NSLog() inside the prepareForSegue, but it is not triggered.
Do you guys have any idea what I am doing wrong? I am pretty new to this, so I still haven't found out this whole iPhone development thing. So bare over with me if the solution is simple :o).
Thanks in advance!
You have a name for the segue, so does that mean you created it by dragging from a button or table view cell to the other view controller and then selected it and named it in xcode? if you are programmatically changing the view it wont be called but you can manually call a method before swapping views to prepare
I had a similar issue in going about sharing information in ios between views where the answer may be helpful.
In particular from the answer on that post where he says:
"in your .m file you would trigger you segue - maybe on a button or some action. sounds like you already have this:"
[self performSegueWithIdentifier:#"viewB" sender:self];
--
Swapping your segue name in of course.