views:

192

answers:

3

I have a connection request working using the stringWithContentsOfURL:encoding:error: method from NSString. I want to be able to retry the connection if it fails the first time. I was going to rewrite the function to use the timeout functionality of NSURLRequest, but I think I'd really like to use multiple retries before failing out.

Aside from doing something crude, like a counter loop, is there an accepted way in Objective-C to retry a URL reuest for data?

EDIT: Ok, I implemented NSURLConnection to get the data I'm interested in, and have added some rudimentary handling for errors using NSError. Here is my initial stab at this:

- (id)initWithURL:(NSURL*)aURL {
    NSError     *error      = nil;
    NSURLResponse   *response   = nil;

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:aURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];

    NSData *data = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];

    NSString *xmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    if (response == nil) {
        if (error) {
            NSLog(@"Error has occurred: %@", [error localizedDescription]);
        }
    }
}

Note: I haven't implemented a strategy to fail gracefully yet, I'm just logging the error for now.

Using this code (or any suggested improvements), what would be the best way to implement a retry strategy here?

+4  A: 

Don't use +stringWithContentsOfURL:. Use a proper NSURLConnection. It will tell you why the load failed.

Mike Abdullah
Although I don't think this is an answer to the question, it's a good thing to begin with.
JoostK
I'm going to use the NSURLConnection and leverage NSError to get a reason as to why the operation might have failed. What about a retry scenario? Are there any commonly used patterns to retry the connection?
Mark Struzinski
A: 

emphasized text

ramil diamante
A: 

I don't think the counter approach is so bad. So long as this function call is not on the main bread, blocking the UI, then there is probably not much else you could do. Maintain a counter of how many times you want to retry, then in your if block try again and increment the counter.

darren