在iOS中使用AFNetworking,确定故障响应是服务器错误还是连接错误的最佳方法是什么?
例如,如果由于连接错误导致上传失败,我可能希望在一段时间间隔后自动重试上传。相反,如果上传因服务器错误而失败,我将永久停止尝试请求。 (我不想重试的错误将是大多数400和500错误。)
请告诉我如何才能最轻松地确定我是否只是看到连接错误或者我是否看到服务器错误?
答案 0 :(得分:0)
我使用以下UIImageView类别。它会在5秒延迟后尝试重新加载图像。
h file:
#import "UIImageView+AFNetworking.h"
@interface UIImageView (ConvenienceAdditions)
- (void)setAutoRetryImageWithURL:(NSURL *)url;
- (void)setAutoRetryImageWithURL:(NSURL *)url completion:(CompletionBlockCommon)block;
- (void)setAutoRetryImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage completion:(CompletionBlockCommon)block;
- (void)setAutoRetryImageWithURLRequest:(NSURLRequest *)urlRequest placeholderImage:(UIImage *)placeholderImage completion:(CompletionBlockCommon)block;
@end
m file:
#import "UIImageView+ConvenienceAdditions.h"
static NSTimeInterval kDGImageReloadingAttemptInterval = 5;
@implementation UIImageView (ConvenienceAdditions)
- (void)setAutoRetryImageWithURL:(NSURL *)url
{
[self setAutoRetryImageWithURL:url completion:nil];
}
- (void)setAutoRetryImageWithURL:(NSURL *)url completion:(CompletionBlockCommon)block
{
[self setAutoRetryImageWithURL:url placeholderImage:nil completion:block];
}
- (void)setAutoRetryImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage completion:(CompletionBlockCommon)block
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setAutoRetryImageWithURLRequest:request placeholderImage:placeholderImage completion:block];
}
- (void)setAutoRetryImageWithURLRequest:(NSURLRequest *)urlRequest placeholderImage:(UIImage *)placeholderImage completion:(CompletionBlockCommon)block
{
__weak typeof (self) weakImageView = self;
[self setImageWithURLRequest:urlRequest placeholderImage:placeholderImage success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
__strong __typeof(weakImageView)strongImageView = weakImageView;
if (block){
block(image, nil);
}
else{
strongImageView.image = image;
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
if (error.code == NSURLErrorCancelled){ // Check error's code
return ;
}
else if (response.statusCode >= 400) // Check response's code
{
return;
}
else{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kDGImageReloadingAttemptInterval * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[weakImageView setAutoRetryImageWithURLRequest:urlRequest placeholderImage:placeholderImage completion:block];
});
}
}];
}
@end
应该按照以下方式使用:
[someImageView setAutoRetryImageWithURL:someImageURL];