24

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?

4

4 に答える 4

41

timeoutIntervalは接続用です。Webビューが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

私の方法は受け入れられた答えに似ていますが、タイムアウト時にstopLoadingを実行し、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 に答える