iOS应用-设置UIWebView加载的超时 [英] iOS App - Set Timeout for UIWebView loading
问题描述
我有一个简单的iOS本机应用程序,可加载单个UIWebView.如果应用程序无法在20秒内完全完成将初始页面加载到webView中,我希望webView显示错误消息.
I have a simple iOS native app that loads a single UIWebView. I would like the webView to show an error message if the app doesn't COMPLETELY finish loading the initial page in the webView within 20 seconds.
我这样在我的viewDidLoad
中加载webView的URL(简化):
I load my URL for the webView within my viewDidLoad
like this (simplified):
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com"] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:20.0]];
上面的代码中的timeoutInterval
实际上并没有做"任何事情,因为Apple在操作系统中将其设置为实际上不会超时240秒.
The timeoutInterval
within the code above does not actually "do" anything, as Apple has it set within the OS to not actually time out for 240 seconds.
我已设置我的webView didFailLoadWithError
操作,但是如果用户具有网络连接,则永远不会调用它. webView只是继续尝试在我的networkActivityIndicator旋转的情况下进行加载.
I have my webView didFailLoadWithError
actions set, but if the user HAS a network connection, this never gets called. The webView just continues to try loading with my networkActivityIndicator spinning.
是否可以为webView设置超时?
Is there a way to set a timeout for the webView?
推荐答案
timeoutInterval用于连接.将webview连接到URL后,您将需要启动NSTimer并进行自己的超时处理.像这样:
The timeoutInterval is for connection. Once webview connected to the URL, you'll need to start NSTimer and do your own timeout handling. Something like:
// define NSTimer *timer; somewhere in your class
- (void)cancelWeb
{
NSLog(@"didn't finish loading within 20 sec");
// do anything error
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[timer invalidate];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
// webView connected
timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(cancelWeb) userInfo:nil repeats:NO];
}
这篇关于iOS应用-设置UIWebView加载的超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!