网络请求af直接报错code=-1005问题总结
方法一
将报错的接口记录下来重新请求一次,在failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) block回调中添加以下代码
if (error.code == -1005) {
if (self.code_1005_method_count_dic == nil) {
self.code_1005_method_count_dic = [[NSMutableDictionary alloc] init];
[self.code_1005_method_count_dic setObject:@(1) forKey:REPLACE_NIL_OBJECT(action)];
}else {
int count = [self.code_1005_method_count_dic[action] intValue];
if (count >= 5) {
DLog(@"超过5次未成功接口action=%@",action)
responseBlock(@{});
return ;
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ dispatch_group_t downloadGroup = dispatch_group_create();
dispatch_group_enter(downloadGroup);
dispatch_group_wait(downloadGroup, dispatch_time(DISPATCH_TIME_NOW, 3000000000)); // Wait 5 seconds before trying again. dispatch_group_leave(downloadGroup);
dispatch_async(dispatch_get_main_queue(), ^{
//重新请求的方法
[self reset1005requestWithAction:action Param:param OnFinished:responseBlock];
});
});
DLog(@"当前接口action=%@连接丢失重新发起",action)
return;
}
方法二
通过多次测试验证,发现将APP与服务端的长链接关闭后,该问题得到解决;因此我们需要在网络请求头里对connection字段进行处理,该字段默认为keep-live保持长链接,修改如下
[self.manager.requestSerializer setValue:@"close" forHTTPHeaderField:@"Connection"];
以上作为该次问题记录,网上找了很久,多数为第一种解决办法,第二种方法目前测试能一次性解决不再报错-1005,暂未发现有其他影响
网友评论