封装网络工具类
Posted 农民农民农民
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装网络工具类相关的知识,希望对你有一定的参考价值。
// HFNetWorkTools.h #import <Foundation/Foundation.h> typedef void(^callBack)(); @class AFHTTPSessionManager; @interface HFNetWorkTools : NSObject @property(nonatomic,copy)AFHTTPSessionManager *manager; @property(nonatomic,copy)callBack block; + (instancetype)sharedInstace; - (void)getHighPingpaiListSuccess:(void(^)(id responseObject) )success failure:(void (^)(NSError *error))failure; @end //HFNetWorkTools.m #import "HFNetWorkTools.h" #import "AFNetworking/AFNetworking.h" static HFNetWorkTools *instance; @implementation HFNetWorkTools + (instancetype)sharedInstace { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (instance == nil) { instance = [[self alloc]init]; instance.manager = [AFHTTPSessionManager manager]; instance.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil]; //默认的是二进制 将其换成JSON类型的 instance.manager.requestSerializer = [AFJSONRequestSerializer serializer]; } }); return instance; } /** * @param url url * @param parms 参数 * @param success 请求成功 * @param failure 请求失败 */ - (void)PostWithUrl:(NSString *)url parms:(NSDictionary *)parms success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure { [self.manager POST:url parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { success(responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { failure(error); }]; } - (void)getHighPingpaiListSuccess:(void(^)(id responseObject) )success failure:(void (^)(NSError *error))failure { [self PostWithUrl:@"http://iosapi.itcast.cn/car/highcarlist.json.php" parms:@{@"accountid":@"1"} success:^(id responseObject) { success(responseObject); } failure:^(NSError *error) { failure(error); }]; } @end HFModel.h #import <Foundation/Foundation.h> @interface HFModel : NSObject @property(nonatomic,copy)NSString *carBrandId; @property(nonatomic,copy)NSString *name; @property(nonatomic,copy)NSString *url; @end HFModel.m #import "HFModel.h" @implementation HFModel @end 在viewcontroller中调用网络工具接口 #import "ViewController.h" #import "HFModel.h" #import "HFNetWorkTools.h" #import "AFNetworking.h" #import "YYModel.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //获取网络数据 [[HFNetWorkTools sharedInstace] getHighPingpaiListSuccess:^(id responseObject) { // NSLog(@"%@",responseObject); //字典转模型 NSArray *arr = [NSArray yy_modelArrayWithClass:[HFModel class] json:responseObject[@"data"][@"high"]]; NSLog(@"%ld",arr.count); } failure:^(NSError *error) { NSLog(@"%@",error); }]; } @end
以上是关于封装网络工具类的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段14——Vue的axios网络请求封装
elasticsearch代码片段,及工具类SearchEsUtil.java