James Sedman
James Sedman

Reputation: 93

Load WKWebView in background/off screen

Is there a way to load a WKWebView in the background/off-screen so I can hide the loading behind another view?

Upvotes: 6

Views: 4812

Answers (1)

Viktor_DE
Viktor_DE

Reputation: 286

You can add the WKWebView to the view hierarchy but its x is your current width, so it lays out of the screen but within the rendering hierarchy.

Add WKNavigationDelegate to your class and add it to the webView like

webView.navigationDelegate = self

Then implement the following function:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation)

This function and some others are called when the webview finished loading the content, BUT this does not include the 100% finished rendering. After that there is still some time required for rendering, the time consumption for this depends on the content that was loaded.

There currently is no callback for the 100% finished loading and rendering, so if you know the files, you can calculate or use a fix delay before moving the webView into the visible rect.

OR

If you feel fine with that, you observe private values in the webview and move your webview after those value changes to your preferred state. This looks for example like that:

class MyCustomWKWebView: WKWebView {

func setupWebView(link: String) {
    let url = NSURL(string: link)
    let request = NSURLRequest(url: url! as URL)
    load(request as URLRequest)
    addObserver(self, forKeyPath: "loading", options: .new, context: nil)
}

override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

    guard let _ = object as? WKWebView else { return }
    guard let keyPath = keyPath else { return }
    guard let change = change else { return }

    switch keyPath {
    case "loading":
        if let val = change[NSKeyValueChangeKey.newKey] as? Bool {
            //do something!
        }
    default:
        break
    }
}

deinit {
    removeObserver(self, forKeyPath: "loading")
}
}

Upvotes: 4

Related Questions