0

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

sinfils
  • 19
  • 1
  • 7

2 Answers2

0

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
0

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];
}
W.K.S
  • 8,845
  • 13
  • 67
  • 115
  • it makes the array loops indefinitely. – sinfils Nov 03 '16 at 13:14
  • First remove your `-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath` method and then use `- (void)scrollViewDidScroll:(UIScrollView *)scrollView`. – W.K.S Nov 03 '16 at 13:15
  • If it still doesn't work, try overriding `- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView` instead of `- (void)scrollViewDidScroll:(UIScrollView *)scrollView`. – W.K.S Nov 03 '16 at 13:21
  • i've tried overriding (void)scrollViewDidEndDecelerating , (void)scrollViewDidScroll and (void)scrollViewDidEndDecelerating but my currentpage index still gets incremented by 8 everytime. – sinfils Nov 08 '16 at 09:37
  • Would you mind sharing the code of your ViewController? I can look into this issue for you tonight? – W.K.S Nov 08 '16 at 13:20