Oliver Zhang Oliver Zhang - 11 months ago 95
Swift Question

Detecting whether a WKWebView has blanked

I am building a simple iOS app using SWIFT. It loads a single page app in WKWebView in the main view full screen. Clicking advertisement would open another WKWebView in a new scene presented modally. However, if I click several pages in the new scene and go back to the main view, the main view has a 50% chance to go blank.

When the main view goes blank, it disappears from the Safari inspector and webView.reload() doesn't work. But loadHTMLString works. So I can do something like this:

1. override func viewWillAppear(animated: Bool) {
2. super.viewWillAppear(false)
3. if pageStatus == .BackFromAdScene {
4. if webView is Blank {
5. loadFromLocal()
6. }
7. }
8. }

I'm curious about what is the simplest way to detect whether a WKWebView is Blank? In other words, how should I write line 4?

Answer Source

In Objective-c I did it with this trick:

    [self.webView evaluateJavaScript:@"document.querySelector('body').innerHTML" completionHandler:^(id result, NSError *error) {
       if (!result || ([result isKindOfClass:[NSString class]] && [((NSString *)result) length] == 0)) {
       // reload your page