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 (err开发者_开发知识库or) {
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?
Don't use +stringWithContentsOfURL:
. Use a proper NSURLConnection. It will tell you why the load failed.
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.
精彩评论