上面是后端同学按照照module的方式开发的服务,在整个的项目中请求中前缀相同而每个module都有自己的前缀,结合起来整个请求URL格式就可以拆分为
HOT:PORT?commonpath+module path + querypath?参数
那么我们怎么在这些众多的的网络中去方便管理我们的多变的url呢?正如我们的标题一样我们采用category将统一的网络请求拆分到不同的文件中---类似服务端的module一样将器拆分到不同的文件中进行管理
比如上面的我们将通过用的网络请求放置到ApiFetch这个类中,让其管理通用的数据参数:token http header等……
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
if ([[AppManager manager] userHasLogin]) {
[manager.requestSerializer setValue:[AppManager manager].token
forHTTPHeaderField:@"token"];
}
NSString * url = [NSString stringWithFormat:@"%@:%d%@",HOST,PORT,api];
[manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
AppModel *modelValue = [AppModel modelWithJSON:responseObject];
if (success) {
success(modelValue,responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error,api);
}];
然后是与服务端的mould保持一致我们进行各模块的网络请求管理以便根据某一某块的特殊要求作出变化,例如,user模块中
-(void)userGetFetch:(NSString *)url
query:(NSDictionary *)query
onSuccess:(void (^)(AppModel * _Nonnull modelValue, id _Nonnull responseObject))onSuccess
onFailure:(void(^)(NSString * message, NSString * shortLink)) onFailure{
NSString * path = [NSString stringWithFormat:@"/user%@",url];
[self getFetch:path
query:query
onSuccess:onSuccess
onFailure:onFailure];
}
对于整个url最终格式我们已经说过了,对于user这个模块中url中附带一个module对应的参数---user,对应的Oder也会添加一个order作为模块url参数的前缀
然后是模块对应的url的管理啦:
如上图每个模块都有自己的path对应url,我们可以统一的防止在category对应的头文件中
总之一句话就是分而治之,将杂而乱的url分化到不同的模块中去,按照每个模块的特性去进行管理
最后我们看看怎么使用吧
user模块的网络请求实例
NSDictionary * params = @{@"phone":account,
@"password":password
};
@weakify(self)
[[ApiFetch share] userGetFetch:USER_PHONE_LOGIN
query:params
holder:self
dataModel:UserInfo.class
onSuccess:^(NSObject * _Nonnull modelValue, id _Nonnull responseObject) {
[weak_self loginSuccessWithUserInfo:modelValue];
}];
info模块对应的请求
[[ApiFetch share] infoGetFetch:INFO_HOME_GEOGRAPHY
query: requestParams
holder:self
dataModel:InfoGeography.class onSuccess:^(NSObject * _Nonnull modelValue, id _Nonnull responseObject) {
InfoGeography *infoGeography = (InfoGeography*)modelValue;
self.headView.wCenterLabel.text = infoGeography.address;
self.headView.wLeft1Label.text =infoGeography.pm25;
self.headView.wLeft2Label.text = @"PM25";
self.headView.wRight1Label.text = [NSString stringWithFormat:@"%@ %@",infoGeography.temperature,infoGeography.weather];
self.headView.wRight2Label.text = infoGeography.wind;
}];
我们通过请求函数可以看出带有很明确的模块感,比如user模块的请求带个函数带个user , info模块带个info?