由于前期宏定义,造成如下代码较多
//获取账户信息
#define lbUserinfoAddress lbBaseApiAddress@"user_info.do"
//下单
#define lbCreatOrderAddress lbBaseApiAddress@"create_order.do"
//撤销订单
#define lbCancelOrderAddress lbBaseApiAddress@"cancel_order.do"
实际部署的服务器在不同的网络线路(联通,移动,长城等)下域名解析还是其他什么原因造成有些线路访问不了,所以这里后台配置了多个域名,在程序中出现请求失败切换线路,目前简单实现是在afnetworking请求失败的回掉里边处理,相对代码改动比较少,侵染也比较小.
就以post举例说明
+(void)requestApiWithMethodPost:(NSString *)url param:(NSMutableDictionary *)param thenSuccess:(void (^)(id responseObject))success fail:(void (^)(void))fail;
{
NSString *newurL=[url stringByReplacingOccurrencesOfString:NetStatusURLStr withString:@""];
newurL = [self dealNowIPHostUrlWithUrl:newurL];
[self showLoadingWithURLStr:newurL];//loading加载图
AFHTTPSessionManager *manager = [self singleManager];
[self setLanguageWithAFHTTPSessionManager:manager];
[manager.requestSerializer setValue:@"zh-CN" forHTTPHeaderField:@"accept-language"];
[manager POST:newurL parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
id response = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
!success ? : success(response);
[self dealWithResponse:response Url:url Param:param];
});
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self dealWithError:error];//(此处切换ip处理)
// [XLUtil showMessage:RDLocalizedString(@"网络错误")];
dispatch_async(dispatch_get_main_queue(), ^{
!fail ? : fail();
});
}];
}
+(void)dealWithError:(NSError *)error{
[self changeNetworkIpUrlIndex];
if(error){
LOG(@"网络错误");
LOG(@"原始错误信息:%@",error);
}
[SVProgressHUD dismiss];
}
#pragma mark -- 切换IP地址
/**处理当前请求的URL*/
+(NSString *)dealNowIPHostUrlWithUrl:(NSString *)urlStr{
if (![urlStr isEqualToString:TestLBURL] &&
![urlStr isEqualToString:WLBURL] &&
![urlStr isEqualToString:PCLBURL]){
NSURL *URL = [NSURL URLWithString:urlStr];
NSString *hostStr = URL.host;
if (![hostStr containsString:@"https"]) {
hostStr = [NSString stringWithFormat:@"https://%@",hostStr];
}
NSString *replaceHostStr = [self getIPHostUrl];
urlStr = [urlStr stringByReplacingOccurrencesOfString:hostStr withString:replaceHostStr];
}
return urlStr;
}
/**获取当前的IP地址*/
+(NSString *)getIPHostUrl{
NSInteger index = [[[NSUserDefaults standardUserDefaults] valueForKey:KNetWorkIpHostIndex] integerValue];
if (index >= [self urlHostArr].count) {
index = 0;
}
return [NSString stringWithFormat:@"%@",[NetWorking urlHostArr][index]];
}
/**备用的ip地址列表*/
+(NSArray *)urlHostArr{
return @[
@"https://xxxx.com",
@"https://xxxx.com",
@"xxxxxx",
];
}
/**切换IP地址*/
+(void)changeNetworkIpUrlIndex{
NSInteger index = [[[NSUserDefaults standardUserDefaults] valueForKey:KNetWorkIpHostIndex] integerValue];
index = index + 1;
if (index >= [self urlHostArr].count) {
index = 0;
}
[[NSUserDefaults standardUserDefaults] setValue:@(index) forKey:KNetWorkIpHostIndex];
}
网友评论