【问题标题】:How to retry a block based URL Request如何重试基于块的 URL 请求
【发布时间】:2014-05-05 17:32:09
【问题描述】:

我正在使用 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 所在的位置完成我的代码 sn-p?

在我的示例中,我在成功获取后调用完成块。 但是我怎样才能再次发送相同的请求呢?

谢谢!

【问题讨论】:

  • 大多数状态码是否值得重试?似乎唯一值得重试的状态码是 500。我对此很陌生,所以我很好奇在连接失败或服务器错误之外重试。

标签: ios objective-c cocoa nsurlrequest


【解决方案1】:

最好有一个重试计数器来防止你的方法永远运行:

- (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];

【讨论】:

  • 重试应该是指数回退+抖动
  • @Avt:在这种情况下,如果 web 服务在重试计数器过期后失败,此方法将不会返回错误信息 IMO。
  • @i.AsifNoor 应在完成块中返回错误。但是,在问题中,完成块“completionBlock”只有一个参数。为了让我的想法更清楚,我决定不让我的代码尽可能接近原始代码。
【解决方案2】:

将您的请求代码放入一个方法中,然后在 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];

}

【讨论】:

  • 类似的问题。如果这必须是一个类方法并且必须将一些参数传递给它怎么办?
  • 是否需要单独的队列? [weakSelf selectorName] 会做对吗?如果服务器出现故障,重试尝试的上限也将防止无限循环。
  • 为了避免无限循环,您可以简单地使用计数器变量。对于队列,您可以使用 dispatch_async 将其放入您想要的任何队列中,以便函数立即返回。
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-30
  • 2019-06-20
  • 1970-01-01
  • 2016-01-04
相关资源
最近更新 更多