我是iOS新手,制作了一个包含JSON解析数据的应用程序,我使用NSURLConnection
并获取数据,但这里我的URL包含分页,所以,我想在tableView滚动时获取分页数据我编写了如下代码
- (void)viewDidLoad
{
page=0;
NSString *path = [NSString stringWithFormat:@"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
当我的表格 View 像这样滚动时,我还会发送第二个请求
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSInteger currentOffset = scrollView.contentOffset.y;
NSInteger maximumOffset = scrollView.contentSize.height- scrollView.frame.size.height;
if (maximumOffset - currentOffset <= 0)
{
page = page + 1;
[self getData];
}
}
-(void)getData
{
NSString *path = [NSString stringWithFormat:@"http://isp.ebizzprojects.com/webservices/testimonial.php?page=%d",page];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
和 NSURLConnection 委托(delegate)方法一样
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_parsedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_parsedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
_parsedData = nil;
_parsedData = [[NSMutableData alloc]init];
[[[UIAlertView alloc]initWithTitle:@"Alert!" message:@"Connection Error" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil]show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString =[[NSString alloc]initWithData:_parsedData encoding:NSUTF8StringEncoding];
NSDictionary *loDict = [responseString JSONValue];
self.responceArray=[loDict valueForKey:@"description"];
self.nameArray=[loDict valueForKey:@"name"];
self.testimonialTable.hidden=FALSE;
[self.testimonialTable reloadData];
}
从我的代码中,当我滚动 TableView 时,我只得到第二页数据,当我的 TableView 滚动时,我想将这两个数据保留到我的 TableView 中,请给我解决方案。 谢谢。
最佳答案
您需要向数组添加新项,例如,为 self.responceArray
和 self.nameArray
创建 NSMutableArray
[self.responceArray addObjectsFromArray:[loDict valueForKey:@"description"]];
[self.nameArray addObjectsFromArray:[loDict valueForKey:@"name"]];
关于ios - 在 iOS 中使用 NSURLConnection 获取分页 URL 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29069989/