zoukankan      html  css  js  c++  java
  • NSMutableUrlRequest自定义封装网络请求

    1.首先封装一个自己的网络请求的类

    **这里表视图引入了第三方类库:MJRefresh 上拉刷新下拉加载

    这是.h文件

    #import <Foundation/Foundation.h>
    
    typedef void(^SuccessBlock)(NSData *data);
    typedef void(^ErrorBlock)(NSError *error);
    
    @interface RequestMethod : NSObject
    
    @property (nonatomic, copy) SuccessBlock successBlock;
    @property (nonatomic, copy) ErrorBlock errorBlock;
    
    
    
    - (void)requestWithUrl:(NSString *)urlString rewuestType:(NSString *)type dictionary:(NSString *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock;
    
    + (void)requestWithUrl:(NSString *)urlString rewuestType:(NSString *)type dictionary:(NSString *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock;
    
    
    
    
    @end

    .m文件:

    /参数字典转换成参数字符串的方法  转码之后就会得到body的NSData对象
    
    - (NSData *)dataFromDictionary:(NSDictionary *)dictionary {
        
        NSMutableArray *mArray = [[NSMutableArray alloc] initWithCapacity:0];
        for (NSString *key in dictionary) {
            NSString *string = [NSString stringWithFormat:@"%@=%@",key,dictionary[key]];
            [mArray addObject:string];
        }
    
        NSString *newString = [mArray componentsJoinedByString:@"&"];
        return [newString dataUsingEncoding:NSUTF8StringEncoding];
        
    }
    
    
    + (void)requestWithUrl:(NSString *)urlString requestType:(NSString *)type dictionary:(NSDictionary *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock {
        
        NetHelper *helper = [[NetHelper alloc] init];
        [helper requestWithUrl:urlString requestType:type dictionary:dictionary successBlock:successBlock errorBlock:errorBlock];
    
    
    }
    
    //请求网络的方法
    
    - (void)requestWithUrl:(NSString *)urlString requestType:(NSString *)type dictionary:(NSDictionary *)dictionary successBlock:(SuccessBlock)successBlock errorBlock:(ErrorBlock)errorBlock {
    
        //因为参数中的block执行的地方是异步请求 那么在Block执行之前 方法已经走完了 那么block就会被回收 所以需要声明属性来记录传入的block 就算是方法内部的block被回收了 也可以执行
        self.successBlock = successBlock;
        self.errorBlock = errorBlock;
        
        NSURLSession *session = [NSURLSession sharedSession];
        //创建对象 采用可变的网络请求对象
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        //如果请求方式是POST
        if ([type isEqualToString:@"POST"]) {
            [request setHTTPMethod:type];//设置请求方式
            if (dictionary.count != 0) {
                [request setHTTPBody:[self dataFromDictionary:dictionary]];
            }
            
        }
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error == nil) {
                self.successBlock(data);
            } else {
                self.errorBlock(error);
            }
            
        }];
    
        [task resume];
    
    }

    2.然后在表视图中使用

    @interface ListTableViewController ()
    
    @property (nonatomic, strong) NSMutableArray *dataArray;
    @property (nonatomic) NSUInteger count;
    
    @end
    
    @implementation ListTableViewController
    
    - (NSMutableArray *)dataArray {
        if (_dataArray == nil) {
            _dataArray = [[NSMutableArray alloc] initWithCapacity:0];
        }
        return _dataArray;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        //下拉刷新
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadUpData)];
        //上拉加载
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadBottomData)];
        
        [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:nil] forCellReuseIdentifier:@"reuse"];
        
        
        
            // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }
    
    - (void)loadUpData {
        
        [NetRequestHelper requestWithUrl:@"http://api2.pianke.me/pub/shop" requestType:@"POST" dictionary:@{@"start":[NSString stringWithFormat:@"%ld",self.count += 10]} successBlock:^(NSData *data) {
            //解析
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDic = dic[@"data"];
            //通过list这个key再取到数据保存的数组
            NSArray *array = dataDic[@"list"];
            for (NSDictionary *dic in array) {
                Model *model = [[Model alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                //结束刷新
                [self.tableView.mj_header endRefreshing];
            });
            
        } errorBlock:^(NSError *error) {
            NSLog(@"刷新失败");
        }];
    
    
    }
  • 相关阅读:
    算法技巧之打表
    Python_爬虫_爬取网络图片信息01
    python_爬虫_爬取京东商品信息
    Python——turtle库学习
    Python学习笔记——函数
    131219流水账
    121219流水账
    081219~111219流水账
    071219流水账
    061219流水账
  • 原文地址:https://www.cnblogs.com/arenouba/p/5304430.html
Copyright © 2011-2022 走看看