如何重试基于块的URL请求

时间:2014-05-05 17:32:09

标签: ios objective-c cocoa nsurlrequest

我使用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上面填写我的代码段?

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

谢谢!

2 个答案:

答案 0 :(得分:16)

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

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

答案 1 :(得分:13)

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

}