Swift WKWebView Loading local file not working on a device
Thank you for any one who tried to answer my question. I have released that this is an error with the WebKit lib that Apple are trying to fix. However I have found a good workaround that required little work.
I open the local file and read its content and then send that string into a webView.loadHTMLString method that compiles the hmtl that was in the file. That way you avoid the issues with iOS not being able to find the path to the local file.
Here is an example of reading a file and then opening it for any one who has the same issues:
let path2 = NSBundle.mainBundle().pathForResource("index", ofType: "html")
var text = String(contentsOfFile: path2!, encoding: NSUTF8StringEncoding, error: nil)!
webView!.loadHTMLString(text, baseURL: url)
Kind regards, Dimitar
Just do this:
if url.isFileURL {
webView.loadFileURL(url, allowingReadAccessTo: url)
} else {
let request = URLRequest(url: url)
webView.load(request)
}
There is a function loadFileURL
on the WKWebView
starting iOS 9 that apparently has to be used when reading data from a file URL.
Strange enough using the load
function with an URLRequest for the file URL does work in the simulators, but not on device - the web view stays blank on the device. Using the loadFileURL
works on device and the simulator.
Using loadHTMLString
unfortunately introduces another problem (local anchors that jump to another position in the same web view are not working anymore) and probably should be avoided until Apple releases a fix for that issue.