我在iOS 8设备上运行时也遇到此问题。这里有更多详细信息,似乎是iOS尝试使用已超时的连接的一种情况。我的问题与该链接中说明的“保持活动”问题不同,但是最终结果似乎相同。
我已经通过在遇到错误-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));
以使该块再次被调用。