**//关键部分**
// NetWorkRequstManger.h文件
#import <Foundation/Foundation.h>
//定义一个枚举类型表示请求类型
typedef NS_ENUM(NSInteger,RequestType) {
GET,
POST
};
//定义一个请求结束的block作为回调
//(返回值类型,名字)
typedef void(^RequestFinish) (NSData *data);
//定义一个请求失败的block作为回调
typedef void(^RequestError) (NSError *error);
@interface NetWorkRequstManger : NSObject
//如果有header就要添加header(字典类型的)
+(void)requestWithType:(RequestType)type urlString:(NSString *)urlString ParDic:(NSDictionary *)ParDic finish:(RequestFinish)finish err:(RequestError)err;
@end
**//NetWorkRequstManger.m文件**
#import "NetWorkRequstManger.h"
@implementation NetWorkRequstManger
//pragma(-)减号表示一块区域
#pragma mark - 封装成+号
+(void)requestWithType:(RequestType)type urlString:(NSString *)urlString ParDic:(NSDictionary *)ParDic finish:(RequestFinish)finish err:(RequestError)err
{
NetWorkRequstManger *manager = [[NetWorkRequstManger alloc] init];
//通过参数的传递,在减号方法中进行数据处理
[manager requestWithType:type urlString:urlString ParDic:ParDic finish:finish err:err];
}
//为什么还有用减号方法(代码的规范)
-(void)requestWithType:(RequestType)type urlString:(NSString *)urlString ParDic:(NSDictionary *)ParDic finish:(RequestFinish)finish err:(RequestError)err
{
//1.将字符串转化为URL
NSURL *url = [NSURL URLWithString:urlString];
//2.创建一个可变的request
NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
//3.1如果是post请求就添加body,如果是get就不用
if (type == POST) {
//3.2设置请求的类型为POST
[mRequest setHTTPMethod:@"POST"];
//3.3.设置body体
if (ParDic.count > 0) {
//将字典转化为NSData的方法
NSData *data = [self DicatoData:ParDic];
//3.4将data放在body体中
[mRequest setHTTPBody:data];
}
}
//4.进行数据请求
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURLSessionDataTask *task = [session dataTaskWithRequest:mRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//该有的判断就应该有
if (data) {
//能进到if语句,说明data是有值的
//在这里使用block的技术将data传递到其他的地方使用
finish(data);
}else
{
err(error);
}
}];
//启动请求
[task resume];
}
#pragma mark - 把参数字典转化为NSData的私有方法
-(NSData *)DicatoData:(NSDictionary *)dic
{
//1.创建1个可变的数组存放所有的键值对
NSMutableArray *array = [NSMutableArray array];
//2.遍历出来所有的键值对
for (NSString *key in dic) {
NSString *KeyAndValue = [NSString stringWithFormat:@"%@ = %@",key,dic[key]];
[array addObject:KeyAndValue];
}
//array = ["a = b","c = d","e = f"]
//3.将数组转化为字符串
NSString *parStr = [array componentsJoinedByString:@"&"];
NSLog(@"%@",parStr);
//a=b&c=d&e=f
//4.将字符转化为NSData
NSData *data = [parStr dataUsingEncoding:NSUTF8StringEncoding];
return data;
}
@end
**//创建一个父类继承自NSObject**
.m文件
@implementation BaseModel
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
NSLog(@"key = %@",key);
}
@end
//创建一个model文件继承自父类(在子类写属性)
#import "BaseModel.h"
@interface ListModel : BaseModel
@property(nonatomic,strong)NSString *coverimg;
@property(nonatomic,strong)NSString *enname;
@property(nonatomic,strong)NSString *name;
@property(nonatomic,strong)NSString *type;
@end
//然后就基本完成工作了,之后就是在引用到的地方解析数据
#import "ViewController.h"
#import "ListModel.h"
#import "NetWorkRequstManger.h"
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
//创建一个可变数组
@property(nonatomic,strong)NSMutableArray *listArray;
@end
@implementation ViewController
//懒加载,是将初始化方法写在get的方法中
//好处,什么时候用,什么时候才去加载.
-(NSMutableArray *)listArray
{
if (!_listArray) {
self.listArray = [NSMutableArray array];
}
return _listArray;
}
- (void)viewDidLoad {
[super viewDidLoad];
//调用创建collcetionView的方法
[self createCollcetionView];
//调用加载数据的方法
[self requestData];
}
//加载数据的方法
-(void)requestData
{
[NetWorkRequstManger requestWithType:GET urlString:READLIST_URL ParDic:@{@"client" :@"1"} finish:^(NSData *data) {
//对传递过来的数据进行解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//解析的实质(一层一层的剥离数据)
NSDictionary *dataDic = [dic objectForKey:@"data"];
NSArray *listArray = [dataDic objectForKey:@"list"];
//遍历
for (NSDictionary *dic in listArray) {
ListModel *model = [[ListModel alloc] init];
[model setValuesForKeysWithDictionary:dic];
[_listArray addObject:model];
}
//不要在子线程中更新UI,还不能创建UI
//拿到数据就刷新
// [_collectionView reloadData];
[self performSelectorOnMainThread:@selector(doMain) withObject:nil waitUntilDone:YES];
} err:^(NSError *error) {
NSLog(@"%@",error);
}];
}
-(void)doMain
{
[_collectionView reloadData];
}
#pragma mark - 创建CollectionView
-(void)createCollcetionView
{
//先创建布局
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.minimumLineSpacing = 2;
layout.minimumInteritemSpacing = 2;
layout.itemSize = CGSizeMake(ScreenWith/3-10, ScreenWith/3-10);
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//创建collectionView
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 150, self.view.bounds.size.width, self.view.bounds.size.height-150) collectionViewLayout:layout];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
//注册cell
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
[self.view addSubview:self.collectionView];
}
#pragma mark - collectionView的代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [self.listArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
ListModel *model = [_listArray objectAtIndexedSubscript:indexPath.row];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:cell.bounds];
nameLabel.text = model.name;
cell.backgroundColor = [UIColor redColor];
[cell addSubview:nameLabel];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网络请求的封装
最新推荐文章于 2024-05-30 21:45:00 发布