在使用initWithContentsOfURL解析提要时,如何设置超时。有时我们的提要返回一个空白响应,然后它将永远尝试解析提要。我想将超时设置为30秒左右,这将弹出一个UIAlertView,然后尝试重新解析提要。
NSURL *feedURL = [[NSURL alloc] initWithString:URL];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:feedURL];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];发布于 2009-12-05 04:55:52
第一种方法:使用延迟选择器的
最简单的方法可能是使用NSObject的performSelector:withObject:afterDelay:方法。您可以这样定义一些方法parsingDidTimeout:
- (void)parsingDidTimeout {
if(self.parsingDidComplete == NO) {
[self.parser abortParsing];
// Create your error and display it here
// Try the fetch and parse again...
}
}这要求您将解析器作为实例变量(self.parser)使用,以便可以从您定义的方法中取消它。它还要求解析器委托跟踪解析器是否已经完成(self.parsingDidComplete,可以在委托的parserDidEndDocument:方法中默认为NO并设置为YES )。这是为了避免中止成功的解析。完成此操作后,只需使用一个简单的
[self performSelector:@selector(parsingDidTimeout) withObject:nil afterDelay:30];30秒后,您的解析中止代码将被调用,您可以执行所需的任何操作。
第二种方法:使用计时器的
通过使用NSTimer而不是NSObject方法调用,可以在timeout方法中使整个方法(可以说)变得更简单。这样,如果解析器成功完成,您可以简单地使计时器无效,从而允许您消除parsingDidTimeout方法中的if子句(因此,还可以消除BOOL ivar)。计时器初始化将如下所示:
NSTimer *timer = [NSTimer timerWithTimeInterval:30.0
target:self
selector:@selector(parsingDidTimeout)
userInfo:nil
repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];发布于 2009-12-05 04:56:36
没有回答您的问题方向,但是如果您使用NSURLConnection下载数据,则可以完全控制请求和响应周期(以及不需要额外线程的异步性)。这就是initWithContentsOfURL:在幕后做的事情。
发布于 2017-03-20 23:33:32
使用NSTimer又称Timer的Swift 3示例
func startParseTimeoutTimer() {
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { (_) in
if (self.busy) {
self.parser?.abortParsing()
self.parser = nil
print("Show UI as NOT busy; we aborted for timeout \(Thread.current.isMainThread)")
}
}
}https://stackoverflow.com/questions/1849513
复制相似问题