【问题标题】:UIWebView show UIActivityIndicator for loading but ignore additional load requests (e.g. javascript loaded advertisements) after page initially loadsUIWebView 显示用于加载的 UIActivityIndi​​cator,但在页面初始加载后忽略其他加载请求(例如 javascript 加载的广告)
【发布时间】:2012-11-08 03:09:35
【问题描述】:

这是一个问答帖。为了通知我在浏览 StackOverflow 的数据库时看到的许多其他用户在这个问题上苦苦挣扎。这些用户都没有得到可靠的答案(而且他们中的大多数人几年前就提出了这个问题,所以我不打算发帖)。


许多人苦苦挣扎的问题如下:

当您尝试在 UIWebView 中加载页面,然后该页面可能通过 iFrame 加载另一个页面或通过 javascript 加载广告时,您最终会再次调用页面加载函数,如果您使用的是 UIActivityIndi​​cator 它会再次被调用并惹恼您的用户。

解决此问题的方法是存储以前的 MainURL 并检查尝试加载的新 MainURL,如果它们匹配则忽略加载函数。 (下面我的答案中的示例代码)

**在网页已经真正加载后将调用webViewDidStartLoad方法的网页示例如下:www.speakeasy.net/speedtest/

【问题讨论】:

    标签: ios uiwebview loading uiactivityindicatorview


    【解决方案1】:
    //Define the NSStrings "lastURL" & "currentURL" in the .h file.
    //Define the int "falsepositive" in the .h file. (You could use booleans if you want)
    //Define your UIWebView's delegate (either in the xib file or in your code `<UIWebViewDelegate>` in .h and `webView.delegate = self;` in .m viewDidLoad)
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        lastURL = [NSString stringWithFormat:@"%@", webView.request.mainDocumentURL];
        if (falsepositive != 1) {
            NSLog(@"Loaded");
            //hide UIActivityIndicator
        } else {
            NSLog(@"Extra content junk (i.e. advertisements) that the page loaded with javascript has finished loading");
            //This method may be a good way to prevent ads from loading hehe, but we won't do that
        }
    }
    
    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {
        NSURL *requestURL = [request mainDocumentURL];
        currentURL = [NSString stringWithFormat:@"%@", requestURL]; //not sure if "%@" should be used for an NSURL but it worked..., could cast `(NSString *)` if we *really* wanted to...
        return YES;
    }
    
    - (void)webViewDidStartLoad:(UIWebView *)webView {
        if ([currentURL isEqualToString:lastURL]) {
            falsepositive = 1;
            NSLog(@"The page is loading extra content with javascript or something, ignore this");
        } else {
            falsepositive = 0;
            NSLog(@"Loading");
            //show UIActiviyIndicator
        }
    }
    
    //make sure you read the //comments// at the top of this code snippet so that you properly define your .h variables O:) Thanks!
    
    
    
    //
    

    【讨论】:

    • 简单而完美的解决方案。花了一天时间调试这个问题,你又救了我一个。请对这个问题的废话投赞成票,这样我们就可以避免其他人浪费他们的时间来试图弄清楚这个问题。
    • @rjm226 很高兴我能帮上忙!
    • 回想起来,我认为我最初的 (int)falsepositive 高于 0 和 1,但在最终版本中我没有,所以如果你愿意,你可以将其设为 BOOL。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多