[英]How to detect if an image in a html is fully loaded in WKWebView?
我正在加載帶有<img>標簽的本地html,例如:
< 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");
});
}
但是,這是一個臨時解決方案。 有更好的解決方案嗎?
我的解決方案是使用JavaScript代碼檢查webView
內容的高度。 如果高度大於或等於一個數字(這意味着在webView內有東西,就是圖像), WKScriptMessageHandler
消息發布到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");
}
}
您可以查看我的演示倉庫以了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.