iOS开发iOS-移动架构师程序员

ECNetworkService-网络请求转模型并本地缓存

2018-05-07  本文已影响52人  even_cheng

本工具可以灵活的在各种项目中使用,工具基于AFNetworking + YYCache + Mantle,实现了一键请求并自定义是否缓存请求结果,并且工具附带一行代码设置请求环境配置。
具体用法如下:

1.将本项目文件夹拖入工程目录.

2.cocopods增加AFNetworking + YYCache + Mantle支持。

3.配置环境参数:
SealInterfacedConst.m文件中设置项目自己的请求地址:

/** 接口前缀-开发服务器*/
NSString *const kEnviromentDevelopment = @"";
/** 接口前缀-测试服务器*/
NSString *const kEnviromentTest = @"";
/** 接口前缀-生产服务器*/
NSString *const kEnviromentProduct = @"";

在appDelegate设置环境:
    [ECConfig shareConfig].environmentType = SEnvironmentTest;

4.根据接口类型创建请求模型:

请求模型继承自 SealBaseParamsModel,用于处理请求参数拼接。
响应模型继承自 SealBaseResponseModel,用于处理服务器响应数据解析转模型


#import "ECBaseParamsModel.h"
#import "ECBaseResponseModel.h"

@interface TestModel : ECBaseParamsModel

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSNumber *pageNumber;

@end

//data子数据
@interface TestResponseItemModel : ECModel

@property (nonatomic, copy) NSString *goodsTitle;
@property (nonatomic, copy) NSString *goodsDesc;

@end

//解析模型
@interface TestResponseModel : ECBaseResponseModel

//总数
@property (nonatomic, copy) NSNumber *totalCount;

@property (nonatomic, strong) NSArray *data;

@end


//模型实现(参照Mantle)
#import "TestModel.h"

@implementation TestModel

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    
    return @{@"title":@"title",
             @"pageNumber":@"pageNumber"
             };
}

@end

@implementation TestResponseItemModel

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    
    return @{@"productId":@"productId",
             @"goodsTitle":@"goodsTitle",
             };
}

@end


@implementation TestResponseModel

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    
    return @{@"data":@"data",
             @"totalCount":@"totalCount"
             };
}

+ (NSValueTransformer *)dataJSONTransformer {
    
    return [MTLJSONAdapter arrayTransformerWithModelClass:[TestResponseItemModel class]];
}

@end

5.创建请求链接:

在 SealInterfacedConst.m 文件中设置接口地址:

.h:
//--------测试---------//
UIKIT_EXTERN NSString *const kTest;

.m:
//--------测试---------//
NSString *const kTest = @"/Test/abc";

6.创建请求

在 SealServer.h 创建请求,并在.m 文件中进行实现,根据项目需要设置请求方法,和缓存与否。

.h:
//--------请求示例---------//
+ (NSURLSessionTask *)getTestDatasWithParameterModel:(TestModel *)parametersModel complete:(ECRequestCompleteBlock)complete;

.m:
//--------请求示例---------//
+ (NSURLSessionTask *)getTestDatasWithParameterModel:(TestModel *)parametersModel complete:(ECRequestCompleteBlock)complete;
{
    ECBaseRequest *request = [ECBaseRequest requestWithPath:kTest parameterModel:parametersModel responseClass:[TestResponseModel class]];
    request.requestType= HttpRequestTypePost;//请求方法
    request.needCache = YES; //是否缓存
    
    return [ECHTTPRequest sendRequest:request complete:complete];
}


最后一步:
在项目中使用SealServer进行接口调用,如果设置了缓存则回调方法会走两次,第一次拿缓存数据,第二次拿网络请求数据,缓存则自动更新。

PS。容错处理请在文件夹下-httpRequest-Exception-Seal_RequestError进行code和description配置.
.h:
//错误类型
typedef NS_ENUM(NSInteger,EC_RequestErrorOption){
  
  //服务器异常
  EC_RequestErrorWithServerConnect = -1004,
  //TOKEN为空
  EC_RequestErrorWithInvalidToken = -1016,
  //网络连接异常
  EC_RequestErrorConnectionError = -1009,
  //请求超时
  EC_RequestErrorRequestTimeOut = -1001,
  //请求地址不存在
  EC_RequestErrorBadRequest = -1011,
  //服务器返回数据类型异常
  EC_RequestErrorResponseFormat,
  //数据转模型失败(数据格式错误)
  EC_RequestErrorBuildModel,
  //请求失败
  EC_RequestErrorUnknown
};

.m:
//初始化异常信息
      //注册异常信息(配置文件)
      _errorDic = [[NSMutableDictionary alloc] init];
      [_errorDic setValue:@"服务器异常" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorWithServerConnect]];
      [_errorDic setValue:@"请登录" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorWithInvalidToken]];
      [_errorDic setValue:@"网络连接异常" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorConnectionError]];
      [_errorDic setValue:@"请求超时" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorRequestTimeOut]];
      [_errorDic setValue:@"数据异常" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorBuildModel]];
      [_errorDic setValue:@"数据格式错误" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorBuildModel]];
      [_errorDic setValue:@"未知错误" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorUnknown]];
      [_errorDic setValue:@"无效的请求" forKey:[[NSString alloc] initWithFormat:@"%ld",(long)EC_RequestErrorBadRequest]];

附上请求示例:

    TestModel* model = [TestModel new];
    model.title = @"test";
    model.pageNumber = @10;
    [SealServer getTestDatasWithParameterModel:model complete:^(Seal_RequestError *error, SealBaseResponseModel *response) {
    
        if (error) {
            NSLog(@"%@",error.getMsg);
            return ;
        }
        
        //拿到数据
        TestResponseModel* responseModel = (TestResponseModel*)response;
        
        //刷新UI
    }];

详细请参见demo: https://github.com/even-cheng/ECNetworkService.git

上一篇下一篇

猜你喜欢

热点阅读