24

我有一个加载单个 UIWebView 的简单 iOS 本机应用程序。如果应用程序未在 20 秒内完全加载 webView 中的初始页面,我希望 webView 显示错误消息。

viewDidLoad像这样(简化)中加载了 webView 的 URL:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com"] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:20.0]];

上面的timeoutInterval代码实际上并没有“做”任何事情,因为 Apple 在操作系统中设置它实际上不会超时 240 秒。

webView didFailLoadWithError设置了我的操作,但是如果用户有网络连接,则永远不会调用它。webView 只是继续尝试加载我的 networkActivityIndi​​cator 旋转。

有没有办法为 webView 设置超时?

4

4 回答 4

41

timeoutInterval 用于连接。webview 连接到 URL 后,您需要启动 NSTimer 并进行自己的超时处理。就像是:

// 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];
}
于 2012-07-23T15:58:54.823 回答
7

所有建议的解决方案都不理想。处理此问题的正确方法是在NSMutableURLRequest自身上使用 timeoutInterval:

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://web.site"]];

request.timeoutInterval = 10;

[webview loadRequest:request];
于 2016-10-03T15:50:14.170 回答
3

我的方式类似于接受的答案,但只是在超时时停止加载并控制在 didFailLoadWithError 中。

- (void)timeout{
    if ([self.webView isLoading]) {
        [self.webView stopLoading];//fire in didFailLoadWithError
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(timeout) userInfo:nil repeats:NO];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self.timer invalidate];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
    //Error 999 fire when stopLoading
    [self.timer invalidate];//invalidate for other errors, not time out. 
}
于 2016-01-07T13:55:46.883 回答
3

Swift 编码人员可以这样做:

var timeOut: NSTimer!

   func webViewDidStartLoad(webView: UIWebView) {
    self.timeOut = Timer.scheduledTimer(timeInterval: 7.0, target: self, selector: Selector(("cancelWeb")), userInfo: nil, repeats: false)
}

func webViewDidFinishLoad(webView: UIWebView) {
    self.timeOut.invalidate()
}

func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    self.timeOut.invalidate()
}

func cancelWeb() {
    print("cancelWeb")
}
于 2016-02-22T13:53:52.107 回答