标签:
// 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
标签:
原文地址:http://www.cnblogs.com/huangfang1314/p/5815083.html