IOS网络笔记--(三方库)上拉加载下拉刷新

来源:互联网 发布:linux内核调试方法 编辑:程序博客网 时间:2024/04/30 23:32

申明:此为本人学习笔记,若有纰漏错误之处的可留言共同探讨

/*

    思路

 用MVC思想,先创建好Cell、Model,导入三方库,遵循协议,先发送请求获取数据,将获取到的数据存进数组。创建UI,创建cell,将数据从数组中取出放入cell。判断是上拉还是下拉,根据状态更新或加载数据。

 

 步骤

 1 引入三方库AFN、WebCache、MJRefresh

 2 写四个方法来获取数据、更新UI、上拉加载、下拉刷新

 3 继承MJRefresh协议初始化上拉刷新、下拉加载设置代理为自己

 4 写refreshViewBeginRefreshing方法,判断当前的状态,如果是上拉就移除所有对象,如果是下拉,就重新获取数据,重新加载数据

 5  在获取数据的方法里发送AFN请求,传回来的数据解析,赋值给数据模型,刷新tableView数据,判断是上拉还是下拉,结束掉上(下)拉刷新。

 6 在更新UI的方法里,初始化TableView,遵循协议、设置行高、注册Cell 加入视图

 7 遵循tableView的协议方法 Cell的数据,从数据模型的那个数组中来,cell的个数是数组的长度

 8 在viewDidLoad中调用写的四个方法

 */


先看看效果图




代码部分:


Model部分

@interface BookModel : NSObject


@property (nonatomic,strong)NSString *title;

@property (nonatomic,strong)NSString *author;

@property (nonatomic,strong)NSString *price;

@property (nonatomic,strong)NSString *imageURL;


@end




View部分

@interface MyCell : UITableViewCell


@property (weak, nonatomic) IBOutlet UIImageView *bookImageView;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UILabel *authorLabel;

@property (weak, nonatomic) IBOutlet UILabel *priceLabel;


@end



Controller部分

#import "ViewController.h"


#import "AFNetworking.h"          // 三方库

#import "UIImageView+WebCache.h"

#import "MJRefresh.h"


#import "MyCell.h"

#import "BookModel.h"


#define URL @"http://api.douban.com/book/subjects?q=test&start-index=%ld&max-%%20results=10&apikey=0f56d0e8157561512e0472b8406023f3&alt=json"


@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,MJRefreshBaseViewDelegate>

{

    NSInteger index;            // URL下标

    NSMutableArray *bookArray;

    UITableView *bookTableView;

    // 下拉刷新数据

    MJRefreshHeaderView *headerView;

    

    // 上拉加载数据

    MJRefreshFooterView *footView;

    

    // 判断状态

    MJRefreshBaseView *baseView;


}

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    bookArray = [[NSMutableArray alloc]init];

    index = 1;

    

    // 调用方法

    [self getData];         // 获取数据

    [self getUI];           // 加载UI

    [self initHeaderView];  // 下拉刷新

    [self initFooterView];  // 下拉加载

    

    

}


#pragma mark - 初始化MJ刷新协议方法

-(void)initFooterView

{

    footView = [[MJRefreshFooterView alloc]initWithScrollView:bookTableView];

    footView.delegate = self;

}


-(void)initHeaderView

{

    headerView = [[MJRefreshHeaderView alloc]initWithScrollView:bookTableView];

    headerView.delegate = self;

}


#pragma mark 刷新和加载的协议方法

-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView

{

    // 记录当前状态

    baseView = refreshView;

    

    if (baseView == headerView) {

        // 下拉刷新

        NSLog(@"下拉刷新");

        if (bookArray.count > 0) {

            [bookArray removeAllObjects];

        }

    }else

    {

        NSLog(@"上拉加载");

    }

    

    [self getData];

    [bookTableView reloadData];


}


#pragma mark 获取数据

-(void)getData

{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer =[AFHTTPResponseSerializer serializer];

    

    NSString *str = [NSString stringWithFormat:URL,index];

    

    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"获取数据成功");

        // 获取了JSON数据,进行解析

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:nil];

        for (NSDictionary *dic  in dict[@"entry"]) {

            BookModel *model =[[BookModel alloc]init];

            model.title = dic[@"title"][@"$t"];

            model.author =dic[@"author"][0][@"name"][@"$t"];

            model.price = dic[@"db:attribute"][3][@"$t"];

            model.imageURL = dic[@"link"][2][@"@href"];

            [bookArray addObject:model];

        }

        

        // 刷新数据

        [bookTableView reloadData];

        

        if (baseView == headerView) {

            // 上拉

            [headerView endRefreshing];

        }else

        {

            // 下拉

            [footView endRefreshing];

        }

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"获取数据失败");

    }];

}


#pragma mark 更新UI

-(void)getUI

{

    // 初始化tableVIew

    bookTableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];

    

    bookTableView.delegate = self;

    bookTableView.dataSource = self;

    bookTableView.rowHeight = 100;

    [bookTableView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellReuseIdentifier:@"cell"];

    [self.view addSubview:bookTableView];

}



#pragma mark - UITableViewDataSource

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

{

    return bookArray.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    BookModel *model = bookArray[indexPath.row];

    MyCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    cell.titleLabel.text = model.title;

    cell.authorLabel.text = model.author;

    cell.priceLabel.text = model.price;

    // 图片加缓存

    [cell.bookImageView sd_setImageWithURL:[NSURL URLWithString:model.imageURL]];

    return cell;

}



附上完整的Demo:http://download.csdn.net/detail/csdn_hhg/9221531


0 0