Objective-C 中接受的重试 URL 请求的方法?
我有一个使用 NSString 中的 stringWithContentsOfURL:encoding:error: 方法工作的连接请求。如果第一次连接失败,我希望能够重试连接。我打算重写该函数以使用 NSURLRequest 的超时功能,但我想我真的很想在失败之前使用多次重试。
除了做一些粗略的事情(例如计数器循环)之外,Objective-C 中是否有一种可接受的方法来重试 URL 请求数据?
编辑: 好的,我实现了 NSURLConnection 来获取我感兴趣的数据,并使用 NSError 添加了一些基本的错误处理。这是我对此的初步尝试:
- (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]);
}
}
}
注意:我还没有实现优雅失败的策略,我现在只是记录错误。
使用此代码(或任何建议的改进),会发生什么这是在这里实施重试策略的最佳方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用
+stringWithContentsOfURL:
。使用正确的 NSURLConnection。它会告诉你加载失败的原因。Don't use
+stringWithContentsOfURL:
. Use a proper NSURLConnection. It will tell you why the load failed.我不认为反击方法有那么糟糕。只要这个函数调用不在主面包上,阻塞 UI,那么您可能就无能为力了。维护一个计数器来记录您想要重试的次数,然后在 if 块中再次尝试并增加计数器。
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.