AFNetworking数据请求(深度封装)

首先你要下载一个AFNetworking框架,不好意思这里没链接^_^

这里写图片描述

上拉下加载下一页

这里写图片描述

我封装的MyAFNetworking

#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"

//声明成功和失败的block代码块的类型
typedef void (^FinishBlock)(id dataString);
typedef void (^ErrorBlock)(NSError* error);

@interface MyAFNetworking : NSObject
//成功时返回信息
@property (strong, nonatomic) FinishBlock finishBlock;
//失败时返回信息
@property (strong, nonatomic) ErrorBlock errorBlock;

//声明一个Get请求的方法
+(void)getUrlStr:(NSString*)urlStr finish:(FinishBlock)finish andError:(ErrorBlock)errors;
//声明一个POST请求方法
+(void)postUrlStr1:(NSString*)urlSte1 postDic:(NSMutableDictionary*)dic finish1:(FinishBlock)finish1 andError:(ErrorBlock)errors;
@end
#import "MyAFNetworking.h"

@implementation MyAFNetworking

//声明一个Get请求的方法
+(void)getUrlStr:(NSString*)urlStr finish:(FinishBlock)finish andError:(ErrorBlock)errors
{
    AFHTTPRequestOperationManager* manger = [AFHTTPRequestOperationManager manager];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        finish(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        errors(error);
    }];
}

//声明一个POST请求方法
+(void)postUrlStr1:(NSString*)urlSte1 postDic:(NSMutableDictionary*)dic finish1:(FinishBlock)finish1 andError:(ErrorBlock)errors
{
    AFHTTPRequestOperationManager* manger = [AFHTTPRequestOperationManager manager];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger POST:urlSte1 parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        finish1(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        errors(error);
    }];
}
@end

ViewController.m中

#import "ViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "First_ViewController.h"
#import "MyAFNetworking.h"

#define AppURL @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=%ld"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (retain) UITableView* tableView;
//数据源
@property (retain) NSMutableArray* dataSource;

@property (assign) NSInteger page;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    _page=1;
    //防止内容视图下滑
    self.automaticallyAdjustsScrollViewInsets = NO;
    //开辟数据源空间
    _dataSource = [NSMutableArray new];
    //创建表格视图
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64) style:UITableViewStylePlain];
    //代理
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    //右边的按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"首次加载数据" style:UIBarButtonItemStyleDone target:self action:@selector(rightAction:)];

    //开始就显示出数据
    [self rightAction:nil];

    //添加表格头部刷新
    __weak __typeof(&*self)weakSelf = self;
    [_tableView addLegendHeaderWithRefreshingBlock:^{
        _page=1;
        [weakSelf.tableView.header beginRefreshing];
        [weakSelf rightAction:nil];
    }];
    //添加尾部加载
    [_tableView addLegendFooterWithRefreshingBlock:^{
        weakSelf.page++;
        [weakSelf.tableView.footer beginRefreshing];
        [weakSelf rightAction:nil];
    }];
}

-(void)rightAction:(UIBarButtonItem*)sender
{
    if (sender) {
        _page = 1;
    }
    NSLog(@"首次加载");
    /*
    //创建AFNetWorking的请求数据
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    //设置服务器端返回数据类型,当前是以二进制的形式返回数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[NSString stringWithFormat:AppURL,_page] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //这里写真正解析代码的
        //responseObject 就是完整的服务器返回数据
        //把返回的responseObject转换成json字典
        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"========dic:%@", dic);
        if (_page==1) {
            [_dataSource removeAllObjects];
        }
        [_dataSource addObjectsFromArray:[dic objectForKey:@"applications"]];
        [_tableView reloadData];
        //结束刷新
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"========error:%@", error);
    }];
     */

    //封装Get调用
    [MyAFNetworking getUrlStr:[NSString stringWithFormat:AppURL,_page] finish:^(id dataString) {
        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"========dic:%@", dic);
        if (_page==1) {
            [_dataSource removeAllObjects];
        }
        [_dataSource addObjectsFromArray:[dic objectForKey:@"applications"]];
        [_tableView reloadData];
        //结束刷新
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    } andError:^(NSError *error) {
        NSLog(@"========error:%@", error);
    }];
}

#pragma mark - 表格视图协议
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"哈哈哈哈哈哈哈哈");
    static NSString* cellID = @"cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    NSDictionary* dic = _dataSource[indexPath.row];
    NSLog(@"====%@====",dic);
    cell.textLabel.text = [NSString stringWithFormat:@"%ld.%@",indexPath.row+1,[dic objectForKey:@"name"]];
    return cell;
}

//可以监听到当前用户点击的是哪一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中行
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    First_ViewController* firstVC = [[First_ViewController alloc]init];
    [self.navigationController pushViewController:firstVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

First_ViewController.m中

#import "First_ViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "MyAFNetworking.h"

#define AppURL @"http://api.cy.daoyoudao.com/app/dishlist.do"

@interface First_ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (retain) UITableView* tableView;
@property (retain) NSMutableArray* dataSource;
@end

@implementation First_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //开辟数据源空间
    _dataSource = [NSMutableArray new];
    //防止内容视图下滑
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64) style:UITableViewStylePlain];
    //代理
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    //下载数据的方法
    [self downLoadData];
}

-(void)downLoadData
{
    //请求数据
    //AFHTTPRequestOperationManager* manger = [AFHTTPRequestOperationManager manager];
    //设置返回类型为二进制流
    //manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    //声明一个可变字典
    NSMutableDictionary* dataDic = [NSMutableDictionary new];
    [dataDic setValue:@"100" forKey:@"apkversion"];
    [dataDic setValue:@"醉江月" forKey:@"appname"];
    [dataDic setValue:@"v2.2.1.0703" forKey:@"appversion"];
    [dataDic setValue:@"670" forKey:@"categorycode"];
    [dataDic setValue:@"33285601411781238031" forKey:@"clientid"];
    [dataDic setValue:@"1" forKey:@"curpage"];
    [dataDic setValue:@"0" forKey:@"filtertype"];
    [dataDic setValue:@"0" forKey:@"filtervalue"];
    [dataDic setValue:@"10986" forKey:@"groupid"];
    [dataDic setValue:@"864502023192438" forKey:@"imei"];
    [dataDic setValue:@"460001491957881" forKey:@"imsi"];
    [dataDic setValue:@"com.dd.zjyue" forKey:@"packagename"];
    [dataDic setValue:@"15" forKey:@"pagesize"];
    [dataDic setValue:@"720*1280" forKey:@"resolution"];
    [dataDic setValue:@"11814" forKey:@"shopid"];
    [dataDic setValue:@"4f891256" forKey:@"signature"];
    [dataDic setValue:@"0" forKey:@"unpackid"];
    [dataDic setValue:@"a_4.4.2" forKey:@"versionrelease"];
    [dataDic setValue:@"116.337033,40.045998" forKey:@"xylocation"];
    /*
    //POST方法:第二个参数为请求体,请求体为字典
    [manger POST:AppURL parameters:dataDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [_dataSource addObjectsFromArray:[dic objectForKey:@"getDishList"]];
        [_tableView reloadData];
        NSLog(@"=====================dic=================:%@", dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"==error:%@", error);
    }];
     */

    //封装POST方法
    [MyAFNetworking postUrlStr1:AppURL postDic:dataDic finish1:^(id dataString) {
        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        [_dataSource addObjectsFromArray:[dic objectForKey:@"getDishList"]];
        [_tableView reloadData];
        NSLog(@"===========dic===========:%@", dic);
    } andError:^(NSError *error) {
        NSLog(@"==error:%@", error);
    }];
}

#pragma mark - 表格协议
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellID = @"cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    NSDictionary* dic = _dataSource[indexPath.row];
    NSLog(@"====%@====",dic);
    cell.textLabel.text = [dic objectForKey:@"productinfo"];
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

谢谢大家看到我博客,新手多多关照

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值