本文网络层处理,主要针对request层、task层、manager层、error层、cache层、以及数据返回处理
下面我们来详细分析各个层面我们做了什么
Request层
主要是根据请求头、请求体、请求方式、超时时间返回一个request对象
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:urlPath parameters:params error:nil];
request.timeoutInterval = RequestTimeoutInterval;
[header enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
[request setValue:obj forHTTPHeaderField:key];
}];
Task层
使用AFN根据request生成一个task任务
NSString *methodType = method == LNetworkRequestTypeGET ? @"GET": @"POST";
NSMutableURLRequest *request =[[LURLRequest sharedInstance] requestWithURL:urlPath method:methodType params:params header:header];
NSNumber *taskIdentifer;
NSURLSessionDataTask *task = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
//从task表中删除已经请求的任务
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
[self.taskTable removeObjectForKey:taskIdentifer];
dispatch_semaphore_signal(lock);
!completionHandle?: completionHandle(response, responseObject, error);
}];
cache层
使用NSCache对需要缓存的请求进行处理
- (void)removeObjectForKey:(id)key {
[self.cache removeObjectForKey:key];
}
- (void)setObject:(LNetworkCache *)objct forKey:(id)key {
[self.cache setObject:objct forKey:key];
}
- (LNetworkCache *)objectForKey:(id)key {
return [self.cache objectForKey:key];
}
error层
主要是针对一些报错信息的管理
static NSString *LNoDataErrorTip = @"没有任何报错信息”;
数据返回处理
主要是通过config中传入的取值路径、modal类进行处理
if (config.valuePath.length > 0) {
json = [json valueForKey:config.valuePath];
}
if ([json isKindOfClass:[NSDictionary class]]) {
if (json) {
//数据转模型
result = [config.modelClass yy_modelWithJSON:json];
}else {
formatError = [NSError errorWithDomain:LNoDataErrorTip code:LNetworkTaskErrorNoData userInfo:nil]; }
}
manager层
主要工作是将缓存与task进行结合
在进行task任务前,先根据是否需要缓存以及是否有缓存进行取缓存操作,以及返回报文的处理,缓存设置
NSString *cacheKey;
if (config.cacheValidTimeInterval > 0){
NSMutableString *mutableString = [NSMutableString stringWithString:config.url];
NSMutableArray *paramsKeys = [config.params.allKeys mutableCopy];
if (paramsKeys.count > 1) {
[paramsKeys sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1 compare:obj2];
}];
[paramsKeys enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[mutableString appendFormat:@"&%@=%@", obj, config.params[obj]];
}];
cacheKey = [LHttpTool lMd5String:[mutableString copy]];
LNetworkCache *cache = [[LNetworkCacheManager sharedManager]objectForKey:cacheKey];
//查看内存中是否有
if (!cache.isValid) {
[[LNetworkCacheManager sharedManager] removeObjectForKey:cacheKey];
} else {
NSLog(@"内存有效,内存中获取数据");
handler ? handler(cache.data, nil) : nil;
return @(-1);
}
}
}
再使用RAC,对manager进行扩展
- (RACSignal *)signalTaskWithConfiguration:(LNetworkTaskConfiguration *)config {
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
NSNumber *taskIdentifier = [self dispatchTaskWithConfiguration:config completionHandler:^(id result, NSError *error) {
if (error) {
[subscriber sendError:error];
}else {
[subscriber sendNext:result];
[subscriber sendCompleted];
}
}];
return [RACDisposable disposableWithBlock:^{
[self cancelTask:taskIdentifier];
}];
}].deliverOnMainThread;
}
使用方式
[[[LHttpManager alloc] signalTaskWithConfiguration:configuration] subscribeNext:^(id _Nullable x) {
NSLog(@"RAC 返回报文:%@",x);
}];
生活如此美好,今天就点到为止。。。
网友评论