iOS App - Set Timeout for UIWebView loading

adamdehaven picture adamdehaven · Jul 23, 2012 · Viewed 31.5k times · Source

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.

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]];

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.

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.

Is there a way to set a timeout for the webView?

Answer

mask8 picture mask8 · Jul 23, 2012

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];
}