I have code that loads several web-pages using WKWebView. Is there a way to attach a unique completion handler function to each WKWebView.loadHTMLString call.
I noticed each returns WKNavigation?, but I don't want to use WKNavigationDelegate as this is for all loading events.
By example, right now without a completion handler, I do this:
wkWebView?.loadHTMLString("<p>Loading page #1</p>", baseURL: nil)
I would like a unique completion handler like this:
wkWebView?.loadHTMLString("<p>SLoading page #1</p>", baseURL: nil, completionHandler: {
    print("Loaded page #1. Doing things only required for page #1.")
})
Then for a different load I could change the completion handler:
wkWebView?.loadHTMLString("<p>SLoading page #2</p>", baseURL: nil, completionHandler: {
    print("Loaded page #2")
})
As you yourself rightly say, loadString returns a WKNavigation object for exactly this purpose. So simply make yourself a dictionary that associates that WKNavigation object with a completion handler, which you store when you are called:
var navs = [WKNavigation : () -> ()]()
func loadString(_ s:String, completionHandler:@escaping ()->()) {
    if let nav = wkWebView?.loadHTMLString(s, baseURL:nil) {
        self.navs[nav] = completionHandler
    }
}
Now, acting as the WKWebView's navigationDelegate, when you hear that a page has loaded, you call its corresponding completion handler:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    if let f = self.navs[navigation] {
        f()
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With