2

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?

Oliver Zhang
  • 499
  • 6
  • 16

2 Answers2

4

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
    }];
Nadzeya
  • 641
  • 6
  • 16
4

user3437673's answer is correct. Here's the SWIFT code for people like me, who came to iOS development just recently.

       self.webView?.evaluateJavaScript("document.querySelector('body').innerHTML") { (result, error) in
            if error != nil {
                // the main web view has turned blank
                // do something like reload the page
            }
        }
Oliver Zhang
  • 499
  • 6
  • 16