我正在使用此方法在我的tableview中实现无限滚动:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView_
{
CGFloat actualPosition = scrollView_.contentOffset.y ;
CGFloat contentHeight = scrollView_.contentSize.height - (700);
NSLog(@"table: %f", self.tableView.frame.size.height);
if (actualPosition >= contentHeight)
{ // self.articles = NULL;
[self makeRequest:currentpage++];
[self.articlesArray addObjectsFromArray:articles];
[self.tableView reloadData];
}
}
我从这样的网络服务中获取数据:
-(void)makeRequest:(int)page1{
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];
}
在我的视图中,控制器的viewDidLoad如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.articlesArray = [[NSMutableArray alloc] init];
self.articles = [[NSMutableArray array]init];
currentpage = 0;
}
在显示新数据之前,我获取了两次数据。我该如何防止这种情况?
答案 0 :(得分:0)
在进行这样的分页请求时,只需跟踪请求是否正在进行中。在文件的界面中跟踪变量,例如:
bool isLoadingMoreData = NO
然后,当你提出请求时:
-(void)makeRequest:(int)page1{
if (self.isLoadingMoreData) {
return
}
self.isLoadingMoreData = YES
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];
self.isLoadingMoreData = NO
}
这是阻止您发出重复请求的简单方法