WKWebView intercept local file requests

626 Views Asked by At

I have a WKWebView in my iOS 11+ app where I need to load custom HTML from local in-memory HTML. I can accomplish this by using webView.loadHTMLString or webview.load(data), which is working fine.

This HTML references some required .js/.css/.png files. For normal web URL requests, WKWebView will just do this on the fly, loading missing files. But in this case, I need to intercept these requests, and provide the file contents, as some of it needs to be dynamically generated. So the .css files etc. I need to serve are not physically present as local files.

I thought this would be just a matter of implementing the decidePolicyFor methods of the WKNavigationDelegate protocol, but for some reason this is not triggered for local subrequests, so how can I accomplish this?

I also tried saving the HTML as a local temporary file and loading it using webView.load(URLRequest), but that does not trigger the delegate either. If it was a web URL, it triggers fine.

1

There are 1 best solutions below

0
On

Let's say you render fullIosAppPath/page.html which has text like <img src="folder/1.png">.
In such case you need to have a file fullIosAppPath/folder/1.png in your app's folder. The WKWebView will load 1.png without any interception - it will just render the image.

So you can parse the HTML file before rendering it, and generate/load the requires resources like 1.png. You can parse an HTML file with frameworks like Kanna, or write some simple parser by yourself.