iOS App - Set Timeout for UIWebView loading

后端 未结 4 1390
小蘑菇
小蘑菇 2021-01-30 14:52

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

相关标签:
4条回答
  • 2021-01-30 15:04

    All of the suggested solutions are not ideal. The correct way to handle this is using the timeoutInterval on the NSMutableURLRequest itself:

    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://web.site"]];
    
    request.timeoutInterval = 10;
    
    [webview loadRequest:request];
    
    0 讨论(0)
  • 2021-01-30 15:19

    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];
    }
    
    0 讨论(0)
  • 2021-01-30 15:21

    My way is similar to accepted answer but just stopLoading when time out and control in 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. 
    }
    
    0 讨论(0)
  • 2021-01-30 15:23

    Swift coders can do it as follow:

    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")
    }
    
    0 讨论(0)
提交回复
热议问题