I updated the code
hi I'm using a tableview populated from a web service in my iOS app
implementing the endless scroll the page number jumps by 4 every time and is not incremented every page has 10 items that are put in an array from the tableview to display.
my code
#interface TableViewController ()
#end
#implementation TableViewController
#synthesize articlesArray;
#synthesize currentpage;
#synthesize articles;
#synthesize page;
#synthesize rowww;
- (void)viewDidLoad {
[super viewDidLoad];
self.articlesArray = [[NSMutableArray alloc] init];
self.articles = [[NSMutableArray alloc]init];
currentpage = 1;
page = 2;
[self fetchData:(int)currentpage];
[self.tableView registerNib:[UINib nibWithNibName:#"ArticleCell" bundle:nil] forCellReuseIdentifier:#"ArticleCell"];
}
-(void)makeRequest:(int)page1{
if ([DGUtilFunctions isInternetAvailable])
{
NSString *urlString = [NSString
stringWithFormat:#"http://url/wp-json/wp/v2/posts?page=%d",(int) page1];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
NSData *theData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
self.articles = [NSJSONSerialization JSONObjectWithData:theData
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"self.articles %#",self.articles);
}
else
{
UIAlertController* _alertView = [ UIAlertController alertControllerWithTitle:nil
message:#"Veuillez vous connecter à internet. " preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){} ];
[_alertView addAction:defaultAction ];
[self presentViewController:_alertView animated:YES completion:nil];
}
}
-(void) fetchData:(int)page2 {
if ([DGUtilFunctions isInternetAvailable])
{
NSString *urlString = [NSString
stringWithFormat:#"http://url/wp-json/wp/v2/posts?&page=%d", (int)page2];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
NSData *theData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
self.articlesArray = [NSJSONSerialization JSONObjectWithData:theData
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"articlesarray %#",self.articlesArray);
}
else
{
UIAlertController* _alertView = [ UIAlertController alertControllerWithTitle:nil
message:#"Veuillez vous connecter à internet. " preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){} ];
[_alertView addAction:defaultAction ];
[self presentViewController:_alertView animated:YES completion:nil];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
CGPoint offset = aScrollView.contentOffset;
CGRect bounds = aScrollView.bounds;
CGSize size = aScrollView.contentSize;
UIEdgeInsets inset = aScrollView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
float reload_distance = 40;
if(y > h + reload_distance) {
NSLog(#"load more rows");
[self makeRequest:(int)page];
page++;
NSLog(#"currentpage %d",(int)page);
[self.articlesArray addObjectsFromArray:self.articles];
[self.tableView reloadData];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section==0)
{
return 0;
}
else{
return [self.articlesArray count] + [self.articlesArray count] / 4;
}
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(self.sidebarMenuOpen == YES){
return nil;
} else {
return indexPath;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
if (3 == (row % 4)) { // or 0 == if you want the first cell to be an ad!
static NSString *MyIdentifier = #"AdCell";
AdViewCell *cell = (AdViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if ((cell == nil) || (![cell isKindOfClass: AdViewCell.class]))
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AdCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell = [[AdViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] ;
}
GADBannerView *bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeMediumRectangle];
double width = (cell.contentView.frame.size.width/2)-(bannerView.frame.size.width/2);
double heigth = (cell.contentView.frame.size.height/2)-(bannerView.frame.size.height/2);
bannerView =[[GADBannerView alloc] initWithFrame:CGRectMake(width,heigth,300,250)];
bannerView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin);
bannerView.adUnitID = #""; //admob
bannerView.rootViewController =self;
GADRequest *request = [GADRequest request];
[bannerView loadRequest:request];
[cell.contentView addSubview:bannerView];
return cell;
}
else {
static NSString *simpleTableIdentifier = #"ArticleCell";
ArticleViewCell *cell = (ArticleViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if ((cell == nil) || (![cell isKindOfClass: ArticleViewCell.class]))
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ArticleCell" owner:self options:nil];
cell = [nib objectAtIndex:1];
cell = [[ArticleViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleTableIdentifier] ;
}
NSInteger offset = indexPath.row / 4;
NSInteger roww = indexPath.row - offset;
rowww = roww;
NSDictionary * tempDictionary = [self.articlesArray objectAtIndex:roww];
NSString *imageUrl = [[self.articlesArray objectAtIndex:roww]objectForKey:#"featured_image"];
imageUrl = [imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[cell.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl ] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image){
// Set your image over here
}else{
//something went wrong
NSLog(#"Error occured : %#", [error description]);
}
}];
});
NSString * title=[tempDictionary valueForKeyPath:#"title"];
cell.titleLabel.text = title;
return cell;
}
}
- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath {
[self performSegueWithIdentifier:#"showarticle" sender:self];
}
// 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 NO;
}
#end
thanks
Imagine a UITableView with 10 UITableViewCells.
Once the UITableView loads, it will call tableView:willDisplayCell:forRowAtIndexPath for each cell. Your implementation increments the page number each time this method is called which causes the page number to jump from 1 to page 10. You should get rid of this method.
Instead, you should rely only on the - (void)scrollViewDidScroll:(UIScrollView *)scrollView callback. Try this:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView_
{
CGFloat actualPosition = scrollView_.contentOffset.y;
CGFloat contentHeight = scrollView_.contentSize.height - (self.tableview.frame.size.height);
if (actualPosition >= contentHeight) {
[self makeRequet:++currentPage];
[self.articlesArray addObjectsFromArray:self.articlesArray];
[self.tableView reloadData];
}
You just need to use this
[tableView insertRowsAtIndexPaths:#[indexPathArray]]
in your request completion handler block
and don't forget to increase your count of rows in
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
Related
I have 2 UITableView. On first UITableView make for search and select cell. After selected cell from UITableView1. It's will show blank data of UITableView2 and show new UITableView2 again with data.
I'm sorry for my bad english language.
I can speak english a little bit.
If you don't understand my question.
Please follow to see pictures below here.
First UITableView: (Click button for go to second UITableView.)
After click button. UITableView2 show blank data.
And auto show new UITableView2 with data again.
UITableView1
#interface SearchByContainerDetailViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableViewWhereHoseList;
#end
#implementation SearchByContainerDetailViewController
#synthesize labelName,strName,txResult,strResult,labelStatus;
NSString *selectedWhereHouse;
GlobalVariable *gloablOnWherehouse;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
labelName.text = strName;
//txResult.text = strResult;
labelStatus.text = #"NULL";
gloablOnWherehouse = [GlobalVariable sharedInstance];
gloablOnWherehouse.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
}
- (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 (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"%lu", (unsigned long)[gloablOnWherehouse.arTableDataSelected count]);
return (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SearchByContainerDetailViewCell";
SearchByContainerDetailViewCell *cell = [self.tableViewWhereHoseList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SearchByContainerDetailViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (gloablOnWherehouse.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:gloablOnWherehouse.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [gloablOnWherehouse.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_Detail"];
NSString *date = [self getString:[cont objectForKey:#"date"]];
NSString *qty = [self getString:[cont objectForKey:#"qty"]];
NSString *stock = [self getString:[cont objectForKey:#"stock"]];
NSString *ord = [self getString:[cont objectForKey:#"ord"]];
NSString *custmr = [self getString:[cont objectForKey:#"custmr"]];
NSString *remarks = [self getString:[cont objectForKey:#"remarks"]];
NSString *invoice = [self getString:[cont objectForKey:#"invoice"]];
NSString *due = [self getString:[cont objectForKey:#"due"]];
NSString *lot = [self getString:[cont objectForKey:#"lot"]];
NSString *gap = [self getString:[cont objectForKey:#"gap"]];
[cell setDate:date setQty:qty setStock:stock setOrd:ord setCustmr:custmr setRemarks:remarks setInvoice:invoice setDue:due setLot:lot setGap:gap];
}
}
}
return cell;
}
- (void) requestEWIServiceFinish:(EWIConnector *)connector responseData:(NSDictionary *)responseData{
NSLog(#"finish %#",connector.serviceName);
NSLog(#"response %#",responseData);
if ([connector.serviceName isEqualToString:#"special_selected_f10"])
{
NSLog(#"finish %#",connector.serviceName);
NSDictionary *content = responseData[#"content"];
NSString *stAlertMes = [content objectForKey:#"alertMessage"];
stAlertMes = [self getString:stAlertMes];
NSLog(#"AlertMSG : %#", stAlertMes);
if (![stAlertMes isEqualToString:#""]) {
NSLog(#"ALERT MESSAGE : %#", stAlertMes);
gloablOnWherehouse.arTableDataSelected = [[NSArray alloc] init];
}
else
{
NSLog(#"HAS DATA");
gloablOnWherehouse.arTableDataSelected = [content objectForKey:#"DataList_SPI_DetailCollection"];
[self.tableViewWhereHoseList reloadData];
labelStatus.text = #"F11";
}
}
else
{
NSLog(#"response %#",responseData);
}
}
- (void) requestEWIServiceFail:(EWIConnector *)connector error:(NSError *)error{
NSLog(#"request fail %#",connector);
}
- (NSString *)getString:(NSString *)string
{
return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (IBAction)btnf10
{
NSMutableDictionary *content = [NSMutableDictionary dictionary];
[content setValue:[[AppSetting sharedInstance] token] forKey:#"ewitoken"];
//[content setValue:gloablOnWherehouse.selectedWhereHouse forKey:#"model_Name"];
[[EWIConnector connector] requestEWIService:#"special_selected_f10" requestData:content delegate:self];
}
UITableView2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
globlOnDisplayEffect = [GlobalVariable sharedInstance];
globlOnDisplayEffect.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
[self.tableViewDetailList reloadData];
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (globlOnDisplayEffect.arTableDataSelected)?[globlOnDisplayEffect.arTableDataSelected count]: 1;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"DisplayEffectQtyViewCell";
DisplayEffectQtyViewCell *cell = [self.tableViewDetailList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DisplayEffectQtyViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (globlOnDisplayEffect.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:globlOnDisplayEffect.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [globlOnDisplayEffect.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_DetailF10"];
NSString *f10_cmpt = [self getString:[cont objectForKey:#"f10_cmpt"]];
NSString *f10_dt = [self getString:[cont objectForKey:#"f10_dt"]];
NSString *f10_item = [self getString:[cont objectForKey:#"f10_item"]];
NSString *f10_lot = [self getString:[cont objectForKey:#"f10_lot"]];
NSString *f10_model = [self getString:[cont objectForKey:#"f10_model"]];
NSString *f10_of = [self getString:[cont objectForKey:#"f10_of"]];
NSString *f10_semi = [self getString:[cont objectForKey:#"f10_semi"]];
NSString *f10_tm = [self getString:[cont objectForKey:#"f10_tm"]];
NSString *f10_uncmp = [self getString:[cont objectForKey:#"f10_uncmp"]];
[cell setf10_cmpt:f10_cmpt setf10_dt:f10_dt setf10_item:f10_item setf10_lot:f10_lot setf10_model:f10_model setf10_of:f10_of setf10_semi:f10_semi setf10_tm:f10_tm setf10_uncmp:f10_uncmp];
}
}
}
return cell;
}
- (void) requestEWIServiceStart:(EWIConnector *)connector{
NSLog(#"start %#",connector.endpoint);
}
TO Check if view controller already push or not.
if(![self.navigationController.topViewController isKindOfClass:[NewViewController class]]) {
[self.navigationController pushViewController:newViewController animated:YES];
}
I use Xcode 6.2, and swift and this particular class with which I am having issue is in ObjectiveC. I am using storyboard, a tabcontroller, and one of the tabs calls thehistoryViewController` which has a table view. In iOS7, when I click on the history tabBarButton, the table view appears with its data.
In iOS8, when I click on history tabBarButton, the table view doesn't appear. If I click on some other tabBarButton, and then again select the history tabBarButton, the table view properly appears with its data.
#import "historyListViewController.h"
#import "QRdatabase.h"
#import "qrdbinfo.h"
#import "historyDetailViewController.h"
#import <UIKit/UIKit.h>
#import "SDWebImage/UIImageView+WebCache.h"
#import "UIImageView+WebCache.h"
#implementation historyListViewController
#synthesize details = _details;
#synthesize qrInfos = _qrInfos;
#synthesize segmentchange;
- (IBAction)valid_in_seg:(id)sender
{
if (segmentchange.selectedSegmentIndex == 0)
{ self.qrInfos = [QRdatabase database].qrdbInfos;
[self.tablelist reloadData];
}
else
{
self.qrInfos = [QRdatabase database].inqrdbInfos;
}
[self.tablelist reloadData];
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
// Scroll table view to the last row
if (_shouldScrollToLastRow)
{
_shouldScrollToLastRow = NO;
[self.tablelist setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
}
[self.tablelist reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tablelist reloadData];
UIImage *myImage =[UIImage imageNamed:#"logo_white_38.png"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage];
[myImageView setFrame:CGRectMake(0, 0, 38, 38)];
self.navigationItem.titleView = myImageView;
self.navigationController.navigationBar.backgroundColor = [UIColor redColor];
segmentchange.tintColor = [UIColor redColor];
_shouldScrollToLastRow = YES;
if (segmentchange.selectedSegmentIndex == 0)
{
self.qrInfos = [QRdatabase database].qrdbInfos;
[self.tablelist reloadData];
}
else
{
self.qrInfos = [QRdatabase database].inqrdbInfos;
[self.tablelist reloadData];
}
self.tablelist.delegate = self;
self.tablelist.dataSource = self;
[self.view addSubview:self.tablelist];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if (segmentchange.selectedSegmentIndex == 0)
{
self.qrInfos = [QRdatabase database].qrdbInfos;
[self.tablelist reloadData];
}
else
{
self.qrInfos = [QRdatabase database].inqrdbInfos;
[self.tablelist reloadData];
}
[self.tablelist reloadData];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
/*- (void)viewDidUnload {
self.qrInfos = nil;
self.details = nil;
}*/
#pragma mark Table view methods
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{ if (segmentchange.selectedSegmentIndex == 0)
{
return 80;
}
else
return 120;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_qrInfos count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (segmentchange.selectedSegmentIndex == 0)
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tablelist dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];}
qrdbinfo *info = [_qrInfos objectAtIndex:indexPath.row];
cell.textLabel.text = info.qr_code;
cell.detailTextLabel.text = [NSString stringWithFormat:#"Date: %#", info.date];
CGSize itemSize = CGSizeMake(30, 30);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[cell.imageView.image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:info.img]
placeholderImage:[UIImage imageNamed:#"img_not_available.png"]];
return cell;
}
else
{
static NSString *CellIdentifier = #"Cell2";
UITableViewCell *cell = [self.tablelist dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
qrdbinfo *info = [_qrInfos objectAtIndex:indexPath.row];
cell.textLabel.text = info.qr_code;
cell.detailTextLabel.text = [NSString stringWithFormat:#"Date: %#", info.date];
return cell;
}
// return cell;
}
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ( !error )
{
UIImage *image = [[UIImage alloc] initWithData:data];
completionBlock(YES,image);
} else{
completionBlock(NO,nil);
}
}];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(segmentchange.selectedSegmentIndex == 0)
{
qrdbinfo *info = [_qrInfos objectAtIndex:indexPath.row];
UIStoryboard* sb = [UIStoryboard storyboardWithName:#"Main"
bundle:nil];
historyDetailViewController * vc = [sb instantiateViewControllerWithIdentifier:#"detail"];
vc.hidesBottomBarWhenPushed = YES;
vc.qrId = info.uniqueId;
[self.navigationController pushViewController:vc animated:YES];
}
else
{
UIAlertView *alerts = [[UIAlertView alloc] initWithTitle:#" Data Unavailable" message:#"No data available for invalid scans" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil, nil];
[alerts show];
}
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
qrdbinfo *info = [_qrInfos objectAtIndex:indexPath.row];
[self.qrInfos removeObjectAtIndex:indexPath.row];
[self.tablelist deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
if(segmentchange.selectedSegmentIndex == 0)
{
// Delete the row from the data source
[[QRdatabase database] deleterow:info.uniqueId];
}
else
{
[[QRdatabase database] deleteinvalidrow:info.uniqueId];
}
[self.tablelist reloadData ];
}
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
}
}
#end
I’m building an article reading app.I’m using AFNetworking third party library to fetch JSON data into the UITableView.
Let say Json link is www.example.com&page=1 gives 1-10 articles and www.example.com&page=2 gives11-20 articles and so on.
I have implemented pagination and scrollViewDidScroll method means when user scroll it gives next ten article.
I’m facing an issue when app launch and UITableView load scrollViewDidScroll method called three times but expected call once.
I’m using increment variable for pagination in scrollViewDidScroll method as i say it call three time and x value goes to 3 and give 30 articles.
When user scroll again it gives next 30 articles.i’m unable to figure out why scrollViewDidScroll method called three times when app is launched.
this is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
tempJson = [[NSMutableArray alloc] init];
[self loadNinjas];
}
- (void)loadNinjas {
NSString *jsonLink=[NSString stringWithFormat:#"www.example.com&page=%d",x];
NSURL *url = [[NSURL alloc] initWithString:jsonLink];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *jsonArray = (NSArray *)responseObject;
for (NSDictionary *dic in jsonArray) {
Json *json = [[Json alloc] initWithDictionary:dic];
[tempJson addObject:json];
}
self.jsons = [[NSArray alloc] initWithArray:tempJson];
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.jsons.count ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier1 = #"ysTableViewCell";
ysTableViewCell *cell1 = [tableView
dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];
cell1.TitleLabel1.text = [self.jsons[indexPath.row] title];
cell1.AuthorLabel1.text = [self.jsons[indexPath.row] author];
[cell1.ThumbImage1 setImageWithURL:[NSURL URLWithString:
[self.jsons[indexPath.row] a_image]]];
return cell1;}
- (void)scrollViewDidScroll: (UIScrollView*)scroll {
CGFloat currentOffset = scroll.contentOffset.y;
CGFloat maximumOffset = scroll.contentSize.height - scroll.frame.size.height;
self.tableView.contentInset = UIEdgeInsetsMake(65, 0, 0, 0);
if (maximumOffset - currentOffset <= -60.0) {
x++;
[self loadNinjas];
[self.tableView addInfiniteScrollingWithActionHandler:^{
}];
[self.tableView reloadData];
}
}
This is a simple code that initializes the tableView with 50 cells and as the user scrolls down the page, adds 20 new cells to the tableView every time it reaches the cell which is 10 cells above the end of the table.
int i;
int lastSeen;
- (void)viewDidLoad {
[super viewDidLoad];
i = 50;
lastSeen = 0;
}
#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 i;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"myCell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%ld", (long)indexPath.row];
lastSeen = (lastSeen < indexPath.row) ? indexPath.row : lastSeen;
return cell;
}
- (void)scrollViewDidScroll: (UIScrollView*)scroll {
if (lastSeen >= (i - 10)) {
i += 20;
//load new data here.
[self.tableView reloadData];
}
}
I'm currently parsing a JSON-feed to my table view in my iOS app. In the JSON-feed there's two different types of posts: "type":"post" and "type":"shared".
When I click on a cell in the Table View, a new view opens with the full posts etc. What I need is to set an if-statement in the didSelectRowAtIndexPath, saying: "If type = post, open this view. Else if type = shared, open this view". So I need to somehow check the json-parameter type. And based on that go to the two different views.
The didSelectRowAtIndexPath method currently looks like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//getting the data I'm passing to the next view, where movies = NSMutableArray
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
// Allocating the Second View I want to open
HomePostsObject *newView = [[HomePostsObject alloc] init];
// passing the data to newView
newView.theMovie = movie;
// presenting the view
[self.navigationController pushViewController:newView animated:YES];
}
And the full code for parsing the data looks like this:
#implementation HomeViewController
#synthesize profilePic;
#synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView;
#synthesize btnFaceBook, btnTwitter, btnTwitter2;
#synthesize strURLToLoad;
#synthesize movies;
#synthesize statsHome;
#synthesize fontForCellText;
#synthesize twitterFollowers;
#synthesize facebookLikes;
#synthesize instagramFollowers;
- (void)viewDidLoad
{
[super viewDidLoad];
// Initializing Data Source
movies = [[NSMutableArray alloc] init];
NSURL *url = [[NSURL alloc] initWithString:#"link.php"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.movies = [[NSArray alloc] initWithArray:JSON];
[self.activityIndicatorView stopAnimating];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return movies.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 85;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"HomeFeedView";
HomeFeedView *cell = (HomeFeedView *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"HomeFeedView" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.backgroundColor = [UIColor clearColor];
}
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
cell.title.text = [movie objectForKey:#"message"];
cell.published.text = [movie objectForKey:#"published"];
cell.twitterName.text = [movie objectForKey:#"celebname"];
return cell;
}
- (NSString *)getTextKey
{
return #"message";
}
- (NSString *)getPostedTime
{
return #"published";
}
- (NSString *)getTwitterName
{
return #"celebname";
}
- (CGFloat)getHeightForText:(NSString *)strText
{
CGSize constraintSize = CGSizeMake(cellTextWidth, MAXFLOAT);
CGSize labelSize = [strText sizeWithFont:fontForCellText constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"labelSize.height = %f",labelSize.height);
return labelSize.height;
}
#end
JSON structure/data:
{
"message":"blablablabla",
"published":"5 hours ago",
"link":"http://google.com",
"unix":1395493814,
"name":"Name",
"story":null,
"picture":"some-pic.jpg",
"type":"shared"
},
{
"message":"blablabla",
"published":"5 hours ago",
"name":"Name",
"unix":1395493814,
"type":"post"
},
In your HomeFeedView.h just add a new property say type.
#property(strong, nonatomic) NSString *type;
Then set this type property in cellForRowAtIndexPath delegate method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"HomeFeedView";
HomeFeedView *cell = (HomeFeedView *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"HomeFeedView" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.backgroundColor = [UIColor clearColor];
}
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
cell.title.text = [movie objectForKey:#"message"];
cell.published.text = [movie objectForKey:#"published"];
cell.twitterName.text = [movie objectForKey:#"celebname"];
cell.type = [movie objectForKey:#"type"];
return cell;
}
and didSelect method write this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//getting the data I'm passing to the next view, where movies = NSMutableArray
HomeFeedView *cell = [tableview cellForRowAtIndexPath:indexPath];
if([cell.type isEqualToString: #"post"]){
// Allocating the Second View I want to open
HomePostsObject *newView = [[HomePostsObject alloc] init];
// passing the data to newView
newView.theMovie = [self.movies objectAtIndex:indexPath.row];
// presenting the view
[self.navigationController pushViewController:newView animated:YES];
}
else{
// Allocating the Second View I want to open
HomePostsObject *newView = [[HomePostsObject alloc] init];
// passing the data to newView
newView.theMovie = [self.movies objectAtIndex:indexPath.row];
// presenting the view
[self.navigationController pushViewController:newView animated:YES];
}
}
I'm trying to filter the data of my Table View which is calling a JSON-file and parses the data to the Table View. I'm getting some strange errors. Here's my code:
#import "FacebookViewController.h"
#import "RNBlurModalView.h"
#import "FacebookPost.h"
#import "TwitterPost.h"
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
#define FONT_SIZE 14.0f
#interface FacebookViewController ()
{
NSInteger refreshIndex;
NSArray *fbPost;
NSArray *pic;
}
#end
#implementation FacebookViewController
#synthesize tweets;
- (void)refreshChannels:(id)sender {
if (tweets.count == 0) return;
// disable UI
self.title = #"Updating...";
self.navigationController.view.userInteractionEnabled = YES;
refreshIndex = 0;
}
- (void) reloadFB {
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *button = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshChannels:)];
self.navigationItem.rightBarButtonItem = button;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu" style:UIBarButtonItemStyleBordered target:self action:#selector(showMenu)];
UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[self.view addGestureRecognizer:gestureRecognizer];
self.myTableView.separatorColor = [UIColor clearColor];
[self issueLoadRequest];
}
- (void)swipeHandler:(UIPanGestureRecognizer *)sender
{
[[self sideMenu] showFromPanGesture:sender];
}
#pragma mark -
#pragma mark Button actions
- (void)showMenu
{
[[self sideMenu] show];
}
#pragma mark - Table view data source
- (void)issueLoadRequest
{
if (changeData.selectedSegmentIndex == 1) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://my-site-facebookparse.php?person=Person"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://my-site-twitterparse.php?person=Person"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
}
- (void)receiveData:(NSData *)data {
if (changeData.selectedSegmentIndex == 1) {
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
} else {
self.tweets1 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
}
- (void)receiveTwitter:(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.tweets1 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (changeData.selectedSegmentIndex == 1) {
return self.tweets.count;
} else {
return self.tweets1.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"FacebookPost";
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
NSDictionary *tweet1 = [self.tweets1 objectAtIndex:indexPath.row];
FacebookPost *cell = (FacebookPost *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"FacebookPost" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (changeData.selectedSegmentIndex == 1) {
cell.fbPost.text = [tweet objectForKey:#"message"];
} else {
cell.fbPost.text = [tweet1 objectForKey:#"tweet"];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 90;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (changeData.selectedSegmentIndex == 1) {
//Open the link
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:#"message"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Message" message:storyLink];
[modal show];
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
} else {
//Öppna länken eller liknande
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:#"tweet"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Message" message:storyLink];
[modal show];
// Spit out some pretty JSON for the tweet that was tapped. Neato.
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
}
}
#end
The table view data is downloading the Twitter post on the launch, even if I have set it to download the Facebook posts. It's very strange... Please help me fix this!
There's a couple of things you need to do. Firstly, you need to set the selected segment index. Before you call [self issueLoadRequest] in viewDidLoad, you should set the selected index like this:
changeData.selectedSegmentIndex = 0;
This will set the first segment to be the selected segment. Also, you'll need to make sure the correct data is loaded when you change the selected segment. To do that, you should add the following to viewDidLoad:
[changeData addTarget:self action:#selector(segmentedControlSelectedIndexChanged:) forControlEvents:UIControlEventValueChanged];
And the companying method, segmentedControlSelectedIndexChanged:
- (void)segmentedControlSelectedIndexChanged:(id)sender
{
[self issueLoadRequest];
}
Now whenever you changed between the Facebook segment and the Twitter segment, it will call the corresponding API, download the data, and update the table view. Depending on the speed on your connection, there may be a small, but noticeable delay between selecting the segment and the table view updating.