#import <AFNetworking/AFNetworking.h>
@interface CZNetworkTools :AFHTTPSessionManager
+ (instancetype)sharedTools;
@end
=========================
#import "CZNetworkTools.h"
@implementation CZNetworkTools
+ (instancetype)sharedTools {
staticCZNetworkTools *tools;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//
NSURL *baseURL = [NSURLURLWithString:@"http://c.m.163.com/nc/"];
NSURLSessionConfiguration *config = [NSURLSessionConfigurationdefaultSessionConfiguration];
//设置请求的超时时长
config.timeoutIntervalForRequest =15;
tools = [[self alloc] initWithBaseURL:baseURL sessionConfiguration:config];
//acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
tools.responseSerializer.acceptableContentTypes = [NSSetsetWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",nil];
});
return tools;
}
@end
========================
#import "CZHeadline.h"
#import "CZNetworkTools.h"
@implementation CZHeadline
+ (instancetype)headlineWithDic:(NSDictionary *)dic {
CZHeadline *headline = [[selfalloc] init];
[headline setValuesForKeysWithDictionary:dic];
return headline;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}
//发送异步请求,字典转模型
+ (void)headlinesWithSuccess:(void(^)(NSArray *array))successBlock errorBlock:(void(^)(NSError *e))errorBlock {
//发送异步请求,获取json数据
[[CZNetworkTools sharedTools] GET:@"ad/headline/0-4.html"parameters:nilprogress:nilsuccess:^(NSURLSessionDataTask *_Nonnull task, NSDictionary *_Nullable responseObject) {
//获取json数据,解析json
//假设rootkey是变化的,获取rootkey
NSString *rootkey = responseObject.keyEnumerator.nextObject;
//获取数组--存储的都是字典
NSArray *array = responseObject[rootkey];
//存储对象的数组
NSMutableArray *mArray = [NSMutableArrayarrayWithCapacity:10];
for (NSDictionary *dicin array) {
//字典转模型
CZHeadline *headline = [selfheadlineWithDic:dic];
[mArray addObject:headline];
}
//调用block
if (successBlock) {
successBlock(mArray.copy);
}
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
if (errorBlock) {
errorBlock(error);
}
}];
}
@end