1

I parse data from API for the first page and add it to UITableView, now pages can be multiple lets say 100, I also get total number of pages from API also. but how will i implement it in tableView for every page and show indicator while scrolling. Have a look at my code

NSURL *theURL = [NSURL URLWithString:@"http://qa.networc.in:1336/api/dispatcher/rideScheduled/:1"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL      cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

//Specify method of request(Get or Post)
[theRequest setHTTPMethod:@"GET"];

//Pass some default parameter(like content-type etc.)
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

[theRequest addValue:token forHTTPHeaderField:@"x-access-token"];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;

NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
if (responseData == nil)
{
    return;
}

NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&theError];
NSLog(@"url to send request= %@",theURL);
NSLog(@"%@",dataDictionaryResponse);



NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  NSLog(@"Response:%@ %@\n", response, error);
                                  if(error == nil)
                                  {

                                      NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                      NSLog(@"Data = %@",text);
                                  }

                                  dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"data"];

                                  NSArray *total =  [dictionary objectForKey:@"total"];
                                  NSLog(@"latlop %@", total);




                                  NSArray *IDArray = [dictionary objectForKey:@"docs"];
                                  for (NSDictionary *Dict in IDArray)
                                  {

                                      NSMutableDictionary *temp = [NSMutableDictionary new];
                                      [temp setObject:[Dict objectForKey:@"_id"] forKey:@"_id"];

                                      NSLog(@"temp %@", temp );

                                      NSString *booknumber = [Dict objectForKey:@"bookingNumber"];
                                      if([booknumber length] != 0)
                                          [temp setObject:booknumber forKey:@"bookingNumber"];

                                      NSMutableDictionary *stp1 = [Dict objectForKey:@"stop1"];

                                      if ([[stp1 allKeys] containsObject:@"address"]) {

                                          [temp setObject:[stp1 objectForKey:@"address"] forKey:@"address"];




                                          ];

                                      }

                                      NSMutableDictionary *stp2 = [Dict objectForKey:@"stop2"];

                                      if ([[stp2 allKeys] containsObject:@"address"]) {

                                          [temp setObject:[stp2 objectForKey:@"address"] forKey:@"address1"];


                                          NSArray *latlongstp2 =  [stp2 objectForKey:@"location"];
                                          [temp setObject:[latlongstp2 objectAtIndex:0] forKey:@"latitude"];
                                          [temp setObject:[latlongstp2 objectAtIndex:1] forKey:@"longitude"];

                                      }



                                      NSMutableDictionary *currentloc = [Dict objectForKey:@"currentLocation"];

                                      if ([[currentloc allKeys] containsObject:@"address"]) {

                                          [temp setObject:[currentloc objectForKey:@"address"] forKey:@"address1"];


                                      }


                                      [getid addObject:temp];

                                  }


                                  if (getid.count>0)
                                  {
                                      [self updateTable];
                                  }



                              }];

[task resume];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;    //count of section
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return [getid count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [getid count] - 1 ) {

    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ScheduleTableViewCell *cell   = [tableView      dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    cell.BookingId.text  = [[getid        objectAtIndex:indexPath.row]objectForKey:@"_id"];
    cell.BookingNo.text  = [[getid objectAtIndex:indexPath.row]objectForKey:@"bookingNumber"];
    cell.stop1.text  = [[getid objectAtIndex:indexPath.row]objectForKey:@"address"];
    cell.stop2.text = [[getid objectAtIndex:indexPath.row] objectForKey:@"address1"];
    cell.Currentloc.text = [[getid objectAtIndex:indexPath.row]  objectForKey:@"address"];


    return cell;
}
Sushil Sharma
  • 2,321
  • 3
  • 29
  • 49
sandeep tomar
  • 303
  • 1
  • 5
  • 17
  • The are number of techniques out there on internet for implementing pagination along with good examples. Try those and modify them to suit your need. Here is a good example - http://www.iosnomad.com/blog/2014/4/21/fluent-pagination – Rohan Sanap May 31 '16 at 05:35
  • @TheRohanSanap sir i don't want to use third party library – sandeep tomar May 31 '16 at 05:37
  • I don't think the example link I specified use any third party library for pagination. They have merely explained logic with example. Anyways, here is another one - https://grokswift.com/rest-tableview-in-swift/ – Rohan Sanap May 31 '16 at 05:42

3 Answers3

4

There are many way to achieve this like following way:

  • First you need to create one global NSMutableArray that load in TableView Delegates and DataSaurce.
  • Now on your api call you need to add That records in global Array.
  • On last cell or the tableview you can call it again with next page URL based on your API and reload table on each Call
  • You can use for loadMore many thirdParty library available on github:

https://github.com/OpenFibers/DragRefreshAndLoadMoreTableDemo

https://github.com/Abizern/PartialTable

https://github.com/robertmryan/UITableView-Bottom-Refresh

Based On your code:

in .h class

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
   NSURL* nextURL;
    int currentPage;

}

in .M Class

- (void)viewDidLoad {

    currentPage = 1;

    [self LoadData];
    [super viewDidLoad];

}


-(void)LoadData
{

    NSURL *theURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://qa.networc.in:1336/api/dispatcher/rideScheduled/:%d",currentPage]];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL      cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

    //Specify method of request(Get or Post)
    [theRequest setHTTPMethod:@"GET"];

    //Pass some default parameter(like content-type etc.)
    [theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

    [theRequest addValue:token forHTTPHeaderField:@"x-access-token"];
    NSURLResponse *theResponse = NULL;
    NSError *theError = NULL;

    NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
    if (responseData == nil)
    {
        return;
    }

    NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&theError];
    NSLog(@"url to send request= %@",theURL);
    NSLog(@"%@",dataDictionaryResponse);



    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {

                                      NSLog(@"Response:%@ %@\n", response, error);
                                      if(error == nil)
                                      {

                                          NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                          NSLog(@"Data = %@",text);
                                      }


                                      currentPage ++;
                                      dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"data"];

                                      NSArray *total =  [dictionary objectForKey:@"total"];
                                      NSLog(@"latlop %@", total);


                                      [getid addObjectsFromArray:total];

                                       [self updateTable];

                                  }];

    [task resume];
}
MRizwan33
  • 2,723
  • 6
  • 31
  • 42
Nitin Gohel
  • 49,482
  • 17
  • 105
  • 144
3

declare a global variable pagingCount and initialize it with 1 in viewdidload.

make this change in your data fetcher method.

NSURL *theURL = [NSURL URLWithString:@"http://qa.networc.in:1336/api/dispatcher/rideScheduled/:%d",pagingCount];

now you will pass this paging count & call your data fetcher method whenever the last cell is about to display. update the paging count with +1

- (void)tableView:(UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == [getid count] - 1 ) {
//call your method of fetching data with paging which will be increased with 1
//increase the pagingCount
pagingCount += 1;

//call your data fetcher
            }
         }
Er. Khatri
  • 1,384
  • 11
  • 29
0

I was done same using following code

#pragma mark --- UIScrollView Delegate Method ---

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float offset = (scrollView.contentOffset.y - (scrollView.contentSize.height - scrollView.frame.size.height));
    btnloadMore.hidden = YES;

    if (offset >= 0 && offset <= 105)
    {
        if(isLoadMoreCheck == TRUE)
        {
            NSLog(@"Hi");
            //btnloadMore.hidden = NO;
            [self addMoreData];
        }
    }

    NSLog(@"Scroll : %f",offset);
}

- (void)addMoreData
{
    isLoadMoreCheck = FALSE;
    isLoadMore = TRUE;
    currentPage++;
    [self getNewsFeeds:currentPage];// Here you can call your method for load next page data
}
Shreyank
  • 1,549
  • 13
  • 24