一、接口URL
自定义一个.H文件
二、各模块接口调用
定义一个handleM类,该类增加一个请求方法
- (void)__requestWith:(NSString *)url dic:(NSMutableDictionary *)dic sel:(SEL)sel isPost:(BOOL)isPost{
self.sel = sel;
NSMutableDictionary *dicp = @{}.mutableCopy;
NSString *baseUrl = K_Base_Url;
dicp[URLS] = [NSString stringWithFormat:@"%@%@",baseUrl,url];
dicp[PRAMAS] = dic == nil ? @{}.mutableCopy : dic;
[self routeTargetName:@"Data" actionName:isPost ? @"postWithDic:": @"getWithDic:" param:dicp];
}
-(void)__requestPicWith:(NSString *)url dic:(NSMutableDictionary *)dic sel:(SEL)sel isPost:(BOOL)isPost{
self.sel = sel;
NSMutableDictionary *dicp = @{}.mutableCopy;
NSString *baseUrl = K_Base_Url;
dicp[URLS] = [NSString stringWithFormat:@"%@%@",baseUrl,url];
dicp[PRAMAS] = dic == nil ? @{}.mutableCopy : dic;
[self routeTargetName:@"Data" actionName:@"updatePicWithDic:" param:dicp];
}
根据模块对该类新建分类例如登录模块
@interface HandleM (Login)
新建登录方法
#import "HandleM.h"
NS_ASSUME_NONNULL_BEGIN
@interface HandleM (Login)
- (void)loginAction:(NSMutableDictionary *)dic;
实现该方法
#import "HandleM+Login.h"
@implementation HandleM (Login)
- (void)loginAction:(NSMutableDictionary *)dic{
[self __requestWith:loginMPath dic:dic sel:@selector(loginAction:) isPost:YES];
}
三、target-action转发
#import <Foundation/Foundation.h>
#import "RequestProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (Set)
@property (nonatomic, strong) id<RequestProtocol>reqDelegate;
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName;
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName param:(id)param;;
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName backParam:(void(^)(NSDictionary *))completion;
- (NSArray *)gettProperities;
@end
NS_ASSUME_NONNULL_END
实现方法
//
// NSObject+Set.m
// RongYiQiangDan
//
// Created by maochengfang on 2020/11/16.
//
#import "NSObject+Set.h"
@implementation NSObject (Set)
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName{
return [self routeTargetName:targetName actionName:actionName param:nil];
}
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName backParam:(void (^)(NSDictionary * _Nonnull))completion{
return [self routeTargetName:targetName actionName:actionName param:completion];
}
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName param:(id)param{
Class targetClass = NSClassFromString(targetName);
SEL actionSel = NSSelectorFromString(actionName);
NSObject *targetObj = [targetClass new];
targetObj.reqDelegate = self;
if([targetObj respondsToSelector:actionSel]){
NSMethodSignature *signature = [targetObj methodSignatureForSelector:actionSel];
NSString *returnType = [NSString stringWithUTF8String:signature.methodReturnType];
if([returnType isEqualToString:@"@"]){
return [targetObj performSelector:actionSel withObject:param];
}else if([returnType isEqualToString:@"v"]||[returnType isEqualToString:@"V"]){
[targetObj performSelector:actionSel withObject:param];
return nil;
}else{
[targetObj performSelector:actionSel withObject:param];
return nil;
}
}else{
NSLog(@"error:%@没有%@方法", targetName, actionName);
return nil;
}
}
- (id<RequestProtocol>)reqDelegate{
return objc_getAssociatedObject(self, @selector(reqDelegate));
}
- (void)setReqDelegate:(id<RequestProtocol>)reqDelegate{
objc_setAssociatedObject(self, @selector(reqDelegate), reqDelegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSArray *)gettProperities
{
unsigned int outCount = 0;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:outCount];
for (int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *name = property_getName(property);
[arrayM addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
return arrayM;
}
@end
四、网络数据请求回调协议
@protocol RequestProtocol <NSObject>
- (void)result:(id)data sel:(NSString *)sel;
- (void)faild:(id)data sel:(NSString *)sel;
五、封装AFNetWorking
定义方法
//
// NSObject+Set.m
// RongYiQiangDan
//
// Created by maochengfang on 2020/11/16.
//
#import "NSObject+Set.h"
@implementation NSObject (Set)
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName{
return [self routeTargetName:targetName actionName:actionName param:nil];
}
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName backParam:(void (^)(NSDictionary * _Nonnull))completion{
return [self routeTargetName:targetName actionName:actionName param:completion];
}
- (id)routeTargetName:(NSString *)targetName actionName:(NSString *)actionName param:(id)param{
Class targetClass = NSClassFromString(targetName);
SEL actionSel = NSSelectorFromString(actionName);
NSObject *targetObj = [targetClass new];
targetObj.reqDelegate = self;
if([targetObj respondsToSelector:actionSel]){
NSMethodSignature *signature = [targetObj methodSignatureForSelector:actionSel];
NSString *returnType = [NSString stringWithUTF8String:signature.methodReturnType];
if([returnType isEqualToString:@"@"]){
return [targetObj performSelector:actionSel withObject:param];
}else if([returnType isEqualToString:@"v"]||[returnType isEqualToString:@"V"]){
[targetObj performSelector:actionSel withObject:param];
return nil;
}else{
[targetObj performSelector:actionSel withObject:param];
return nil;
}
}else{
NSLog(@"error:%@没有%@方法", targetName, actionName);
return nil;
}
}
- (id<RequestProtocol>)reqDelegate{
return objc_getAssociatedObject(self, @selector(reqDelegate));
}
- (void)setReqDelegate:(id<RequestProtocol>)reqDelegate{
objc_setAssociatedObject(self, @selector(reqDelegate), reqDelegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
实现GET POST 方法
- (void)__getDataWithUrl:(NSString *)url params:(NSDictionary *)params resultBlock:(void(^)(id result))block failureBlock:(void(^)( NSError * _Nonnull error))failureblock{
BOOL flag = [self getProxyStatus:url];
if (flag) {
[SVProgressHUD showErrorWithStatus:@"网络异常"];
return;
}
if (![self __judgeUrl:url]) {
return;
}
/**
取缓存
*/
BOOL needCache = [params[@"cache"]boolValue];
if (needCache) {
id result = [self getDataFromLocationWithPathName:url dic:params];
if (result) {
block(result);
}
}
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer.timeoutInterval = 30;
manager.securityPolicy.allowInvalidCertificates = YES;
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSUTF8StringEncoding];
[manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
//无条件的信任服务器上的证书
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
// 客户端是否信任非法证书
securityPolicy.allowInvalidCertificates = NO;
// 是否在证书域字段中验证域名
securityPolicy.validatesDomainName = YES;
manager.securityPolicy = securityPolicy;
NSString *sessionId = [UIKitFactory getCacheValueWithType:LoginValueSESSION];
// NSString *sessionId = @"user:895daf4b-9ddd-4075-a384-8e52ee874aaa";
// //[UIKitFactory getCacheValueWithType:LoginValueSESSION];
[manager.requestSerializer setValue:sessionId forHTTPHeaderField:@"token"];
[manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"systemVersion"];
[manager.requestSerializer setValue:[UIDeviceHardware systemVersion] forHTTPHeaderField:@"systemName"];
[manager.requestSerializer setValue:[UIDeviceHardware platformString] forHTTPHeaderField:@"phoneType"];
[manager.requestSerializer setValue:[UIDeviceHardware appinfoType:1] forHTTPHeaderField:@"version"];
[manager.requestSerializer setValue:[UIDeviceHardware appinfoType:2] forHTTPHeaderField:@"packageName"];
[manager.requestSerializer setValue:@"App Store" forHTTPHeaderField:@"channel"];
NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:params];
[mDic setValue:sessionId forKey:@"token"];
params = mDic.mutableCopy;
[manager GET:url parameters:params headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (block) {
block(responseObject);
//插入缓存
if (needCache) {
[self setDataToLocationData:responseObject pathName:url dic:params];
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failureblock) {
failureblock(error);
}
}];
}
- (BOOL)getProxyStatus:(NSString *)url {
NSDictionary *proxySettings = (__bridge NSDictionary *)CFNetworkCopySystemProxySettings();
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:url]),(__bridge CFDictionaryRef _Nonnull)(proxySettings)));
NSDictionary *settings = [proxies objectAtIndex:0];
NSLog(@"host=%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"port=%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"type=%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]); if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
{ //没有设置代理
return NO;
} else { //设置代理了
return YES;
}
}
- (void)__postDataWithUrl:(NSString *)url params:(NSDictionary *)params resultBlock:(void(^)(id result))block failureBlock:(void(^)( NSError * _Nonnull error))failureblock{
BOOL flag = [self getProxyStatus:url];
if (flag) {
[SVProgressHUD showErrorWithStatus:@"网络异常"];
return;
}
// NSLog(@"flag=====%i",flag);
if (![self __judgeUrl:url]) {
return;
}
/**
取缓存
*/
BOOL needCache = [params[@"cache"]boolValue];
if (needCache) {
id result = [self getDataFromLocationWithPathName:url dic:params];
if (result) {
block(result);
}
}
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
if (![AutoSwitchFlag shared].openAFNet ) {
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
}
manager.requestSerializer.timeoutInterval = 30;
manager.securityPolicy.allowInvalidCertificates = YES;
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSUTF8StringEncoding];
// [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"contentType"];
//无条件的信任服务器上的证书
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
// 客户端是否信任非法证书
securityPolicy.allowInvalidCertificates = NO;
// 是否在证书域字段中验证域名
securityPolicy.validatesDomainName = YES;
manager.securityPolicy = securityPolicy;
NSString* cmdStr = NSStringFromSelector(_cmd);
NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:params];
NSString *sessionId = [UIKitFactory getCacheValueWithType:LoginValueSESSION];
//
[manager.requestSerializer setValue:sessionId forHTTPHeaderField:@"token"];
[manager.requestSerializer setValue:[UIDeviceHardware systemVersion] forHTTPHeaderField:@"systemVersion"];
[manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"systemName"];
[manager.requestSerializer setValue:[UIDeviceHardware platformString] forHTTPHeaderField:@"phoneType"];
[manager.requestSerializer setValue:[UIDeviceHardware appinfoType:1] forHTTPHeaderField:@"version"];
[manager.requestSerializer setValue:[UIDeviceHardware appinfoType:2] forHTTPHeaderField:@"packageName"];
[manager.requestSerializer setValue:@"App Store" forHTTPHeaderField:@"channel"];
params = mDic.mutableCopy;
[manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain",nil,nil]];
NSLog(@"🌰🌰🌰请求URL==========%@\n\n🍇🍇🍇请求sessionId==========%@\n\n🍮🍮🍮请求参数==========%@",url,sessionId,params);
[manager POST:url parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (block) {
block(responseObject);
//插入缓存
if (needCache) {
[self setDataToLocationData:responseObject pathName:url dic:params];
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failureblock) {
failureblock(error);
}
}];
}
- (void)getWithDicNeedCache:(NSMutableDictionary *)dic{
dic[PRAMAS][@"cache"] = @1;
[self getWithDic:dic];
}
- (void)getWithDic:(NSMutableDictionary *)dic{
[self __getDataWithUrl:dic[URLS] params:dic[PRAMAS] resultBlock:^(id result) {
if (self.reqDelegate && [self.reqDelegate respondsToSelector:@selector(result:sel:)]) {
[self.reqDelegate result:result sel:NSStringFromSelector(_cmd)];
}
} failureBlock:^(NSError * _Nonnull error) {
if (self.reqDelegate && [self.reqDelegate respondsToSelector:@selector(faild:sel:)]) {
[self.reqDelegate faild:error sel:NSStringFromSelector(_cmd)];
}
}];
}
- (void)postWithDic:(NSMutableDictionary *)dic{
[self __postDataWithUrl:dic[URLS] params:dic[PRAMAS] resultBlock:^(id result) {
if (self.reqDelegate && [self.reqDelegate respondsToSelector:@selector(result:sel:)]) {
[self.reqDelegate result:result sel:NSStringFromSelector(_cmd)];
}
} failureBlock:^(NSError * _Nonnull error) {
if (self.reqDelegate && [self.reqDelegate respondsToSelector:@selector(faild:sel:)]) {
[self.reqDelegate faild:error sel:NSStringFromSelector(_cmd)];
}
}];
}
最后在HandleM文件中获取到网络请求数据
#import "HandleM.h"
@implementation HandleM
- (void)result:(id)data sel:(NSString *)sel{
}
- (void)faild:(id)data sel:(NSString *)sel{
}