SwiftUI Journey Part 9: WKNavigationDelegate

Posted on May 22, 2022

Next on the task is how to extend the class WKNavigationDelegate so I can call the evaluateJavascript() function.

We used an ' extension' in our existing iOS app using UIKit. But I found out, that this won’t work when using SwiftUI.


extension MyJobsViewController: WKNavigationDelegate {
}

After further Googling, research and internet digging I learned that I need to use makeCoordinator() function.

Creates the custom instance that you use to communicate changes from your view controller to other parts of your SwiftUI interface.

First, I wrote an inner class called Coordinator.


class Coordinator: NSObject, WKNavigationDelegate {
        let parent: OnlineJobsWebView
        
        init(_ parent: OnlineJobsWebView) {
            self.parent = parent
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            webView.evaluateJavaScript(Keys.javascriptRemoveElements, completionHandler: {
                _, error in
            })
        }
}

Then in the main class


struct OnlineJobsWebView: NSViewRepresentable {

     func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

     var url: URL
    
    func makeNSView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateNSView(_ webView: WKWebView, context: Context) {
        webView.navigationDelegate = context.coordinator
        // Evaluate Javascript will now work at this point.
    }
}

This implementation feels a little hacky. Why wouldn’t Apple just introduce a WebView for SwiftUI? Going through all this is just painful.

Hide the pain