Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add unique completion handler to every WKWebView load

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")
})
like image 580
user2560886 Avatar asked Sep 17 '25 03:09

user2560886


1 Answers

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()
    }
}
like image 103
matt Avatar answered Sep 19 '25 20:09

matt