Creating links between WKWebView and Native code
Lucky for us, WKWebView offers everything we need. With a bit of tinkering, we can configure it to do exactly what we need! Setting up a webview is trivial and well-documented, so I’m not going to explain that here. You can either instantiate it through code or simply drag one in your view in Interface Builder and create an outlet for it. I chose to do the latter.
Now, we probably want to do something else than just logging the values we receive, but for the sake of explaining the concept, this will do. Say we’re keeping a list of people in the webview, the addPerson function will be called from the native context to add it to the webview. The sendNameToNative function can be called to send a message back to the native code. Let’s add the last building blocks to get everything working!
The last few steps
You might need to fiddle with this a bit depending on how you set up your views. One thing you might to do is change the frame to be equal to view.frame, and another thing that might fix problems here is adding view = webview after the last line. This might create some other problems.
There’s only one thing left to do here, which is actually sending a message to the webview.
Now that you’ve got the structure laid out, you can go wild:
- Actually handle the response to trigger certain actions in native code, like animations or segues.
- Add more handlers to handle different responses from the webview, creating a tightly-knit connection between the two
Congratulations! If you’re reading this you’ve created a connection between a WKWebView and the native context of your application. This opens a lot of possibilities, and you can take this as far as you want. If you created something awesome with this, please share it with me!