如何重试基于块的URL请求
我使用iOS7的新的URL请求方法来获取数据,如下所示:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self.baseUrl stringByAppendingString:path]]]; NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; NSUInteger responseStatusCode = [httpResponse statusCode]; if (responseStatusCode != 200) { // RETRY (??????) } else completionBlock(results[@"result"][symbol]); }]; [dataTask resume];
不幸的是,我不时得到HTTP响应,指出服务器不可达( response code != 200
),需要重新发送相同的请求到服务器。
如何才能做到这一点? 我如何才能完成我的代码片段上面我的评论// RETRY
?
在我的例子中,成功获取后调用完成块。 但是我怎么能再次发送相同的请求?
谢谢!
把你的请求代码放在一个方法中,并在dispatch_async
块中再次调用它;)
- (void)requestMethod { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self.baseUrl stringByAppendingString:path]]]; __weak typeof (self) weakSelf = self; NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; NSUInteger responseStatusCode = [httpResponse statusCode]; if (responseStatusCode != 200) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{ [weakSelf requestMethod]; }); } else completionBlock(results[@"result"][symbol]); }]; [dataTask resume]; }
最好有一个重试计数器来防止你的方法永远运行:
- (void)someMethodWithRetryCounter:(int) retryCounter { if (retryCounter == 0) { return; } retryCounter--; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self.baseUrl stringByAppendingString:path]]]; __weak __typeof(self)weakSelf = self; NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; NSUInteger responseStatusCode = [httpResponse statusCode]; if (responseStatusCode != 200) { [weakSelf someMethodWithRetryCounter: retryCounter]; } else completionBlock(results[@"result"][symbol]); }]; [dataTask resume]; }
它应该被称为以下方式:
[self someMethodWithRetryCounter:5];