Search code examples
iosobjective-ccocoansurlrequest

How to retry a block based URL Request


I am fetching data using iOS7's new URL request methods, like so:

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

Unfortunately, from time to time I get HTTP responses indicating the server is not reachable (response code != 200) and need to resend the same request to the server.

How can this be done? How would I need to complete my code snippet above where my comment // RETRY is?

In my example I call the completion block after a successful fetch. But how can I send the same request again?

Thank you!


Solution

  • Put your request code in a method and call it again in a dispatch_async block ;)

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