如何检测html中的图像是否在WKWebView中完全加载?

时间:2018-01-03 07:56:22

标签: ios objective-c

我正在使用<加载本地html。 IMG>标记例如:

< img class="icon" src="data:image/png;base64,/9j/4AAQSkZJRgABAQEAlgCWAAD/7gAOQWRvYmUAZAAAAAAA/...

但是,如何检测图像是否已满载?我用它来检测。但是,它似乎不起作用。有时图像被加载,有时它不是。

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    if (webView.isLoading) return;
    ..
    //proceed to load the second html
}

更新

我在didFinishNavigation委托中添加了一个延迟,图片被完美加载:

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
if (webView.isLoading) return;


double delayInSeconds = 3.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    NSLog(@"Do some work");

});

}

然而,这是一个临时解决方案。有更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

我的解决方案是使用javascript代码检查内容的webView高度。如果高度大于或等于数字(这意味着在webView中有内容,则是图像),向webView发送消息并使用WKScriptMessageHandler处理本机代码中的消息。

示例

创建javascript代码。检查内容的高度是否大于50,发布消息以检查图像是否已加载。

NSString* source =
    [NSString stringWithFormat:
                  @"var sizeInterval = setInterval("
                   "function() {"
                   "var h = 0;"
                   "var children = document.body.children;"
                   "for (var c = 0; c < children.length; c++) {"
                   "h += children[c].offsetHeight;"
                   "}"
                   "if (h > 50) {"
                   "clearInterval(sizeInterval);"
                   "window.webkit.messageHandlers.%@.postMessage('loaded');"
                   "}"
                   "},"
                   "100);",
                  kContentLoadedMessage];

WKUserScript* script = [[WKUserScript alloc]
      initWithSource:source
       injectionTime:WKUserScriptInjectionTimeAtDocumentStart
    forMainFrameOnly:YES];

WKUserContentController* contentController =
    [[WKUserContentController alloc] init];
[contentController addUserScript:script];
[contentController addScriptMessageHandler:self name:kContentLoadedMessage];

WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = contentController;

YOUR_WK_WEB_VIEW =
    [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
// Add webView to a view and load html

使用WKScriptMessageHandler处理邮件。

- (void)userContentController:(WKUserContentController*)userContentController
      didReceiveScriptMessage:(WKScriptMessage*)message {
  if ([message.name isEqualToString:kContentLoadedMessage]) {
    NSLog(@"Image was loaded");
  }
}

您可以查看my demo repo以获得更多理解。