我有几个“代理”类,它们继承自“基本代理”。这些类连接到我的服务器并将数据传递给它们的代表。如果状态码为 0,我想以相同的方式处理这些不同的请求。
对于 0 状态码,我想在 5 秒内重试该方法,希望用户的互联网连接有所改善。
东西代理.m
- (void)fetchSomething {
NSString *fullPath = [NSString stringWithFormat:@"%@/route/index.json",MY_BASE_URL];
NSURL *url = [NSURL URLWithString:fullPath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *d = (NSDictionary *)responseObject;
[self.delegate fetchedPolicy:d[@"keypath"]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self handleOperationFailed:operation action:^{
[self fetchSomething];
}];
}];
NSOperationQueue *q = [[NSOperationQueue alloc] init]; [q addOperation:operation];
}
MyBaseProxy.m
- (bool)shouldRetryOperation:(AFHTTPRequestOperation *)o {
return self.retries < [self maxRetries];
}
- (void)handleOperationFailed:(AFHTTPRequestOperation *)o action:(ActionBlock)block {
NSInteger statusCode = o.response.statusCode;
if (statusCode == 0) {
if ([self shouldRetryOperation:o]) {
double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
self.retries++;
block();
});
} else {
self.retries = 0;
[SVProgressHUD showErrorWithStatus:@"Please check your internet connection and try again"];
return;
}
}
self.retries = 0;
处理请求失败的更好方法是什么?我应该继承 AFHTTPRequestOperation 吗?
编辑:删除了令人困惑的文字。当我的意思是“相同的方式”时,我的意思是每个请求,例如。处理所有 500 相同,处理所有 403 相同。我特别要求处理状态代码 0 - 没有互联网连接。