How to determine iFrame finished loading in UIWebView

前端 未结 3 1524
日久生厌
日久生厌 2021-02-06 08:06

In my app, I need a way to tell when my webview is finished loading. It is very easy to do that if content is html. However, my content source is javascript with iFrame inside,

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 08:49

    The only foolproof method I've found is to listen to the three methods that say it's about to start loading, and that it finished loading (plus equivalent for "failed"), and to manually maintain a count for each.

    i.e. something like:

    int outstandingRequests;
    
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        outstandingRequests++;
    }
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
        outstandingRequests--;
    
        if( outstandingRequests < 1 )
        viewLoadingPleaseWait.hidden = TRUE;
    }
    
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
    {
        outstandingRequests--;
    }
    

    I've also usually had to overrid the didFail method - Apple incorrectly uses this to report that e.g. the YouTube player has taken over the handling of a YouTube video. It's NOT a fail, it's a "page was loaded by a different application".

    e.g.

    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
    {
        outstandingRequests--;
    
        if( [error code] == NSURLErrorCancelled )
        {
            NSLog(@"[%@] ...webView CANCELLED loading", [self class] );
        }
        else if( [[error domain] isEqualToString:@"WebKitErrorDomain"]
        && [error code] == 204)
        {
            // no worries ... YouTube, iCal, or etc took over the page load
        }
    }
    

提交回复
热议问题