我也有这个问题,在 iOS 8 设备上运行。这里有更多详细信息,似乎是 iOS 尝试使用已经超时的连接的情况。我的问题与该链接中解释的 Keep-Alive 问题不同,但它似乎是相同的最终结果。
每当我收到错误 -1005 时,我通过运行递归块来纠正我的问题,这使得连接最终通过,即使有时递归可以在连接工作之前循环 100 多次,但是它只增加了一秒钟的运行时间次,我敢打赌,这正是调试器为我打印 NSLog 所需的时间。
以下是我使用 AFNetworking 运行递归块的方法:将此代码添加到您的连接类文件中
// From Mike Ash's recursive block fixed-point-combinator strategy https://gist.github.com/1254684
dispatch_block_t recursiveBlockVehicle(void (^block)(dispatch_block_t recurse))
{
// assuming ARC, so no explicit copy
return ^{ block(recursiveBlockVehicle(block)); };
}
typedef void (^OneParameterBlock)(id parameter);
OneParameterBlock recursiveOneParameterBlockVehicle(void (^block)(OneParameterBlock recurse, id parameter))
{
return ^(id parameter){ block(recursiveOneParameterBlockVehicle(block), parameter); };
}
然后像这样使用它:
+ (void)runOperationWithURLPath:(NSString *)urlPath
andStringDataToSend:(NSString *)stringData
withTimeOut:(NSString *)timeOut
completionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
OneParameterBlock run = recursiveOneParameterBlockVehicle(^(OneParameterBlock recurse, id parameter) {
// Put the request operation here that you want to keep trying
NSNumber *offset = parameter;
NSLog(@"--------------- Attempt number: %@ ---------------", offset);
MyAFHTTPRequestOperation *operation =
[[MyAFHTTPRequestOperation alloc] initWithURLPath:urlPath
andStringDataToSend:stringData
withTimeOut:timeOut];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
if (error.code == -1005) {
if (offset.intValue >= numberOfRetryAttempts) {
// Tried too many times, so fail
NSLog(@"Error during connection: %@",error.description);
failure(operation2, error);
} else {
// Failed because of an iOS bug using timed out connections, so try again
recurse(@(offset.intValue+1));
}
} else {
NSLog(@"Error during connection: %@",error.description);
failure(operation2, error);
}
}];
[[NSOperationQueue mainQueue] addOperation:operation];
});
run(@0);
}
您会看到我使用了一个AFHTTPRequestOperation
子类,但添加了您自己的请求代码。重要的部分是调用recurse(@offset.intValue+1));
以使块再次被调用。