I am attempting to load local images from my local Bundle into my WkWebView but have not been successful.
This is my index.html
:
<div>
<img src='./images/test.png'>
<p>Test Para</p>
</div>
My folder structure:
- web
-- images
-- test.png
-- index.html
- ViewController
Code in ViewController that loads the HTML
Attempt 1:
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: true)
webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlUrl)
Attempt 2:
let url = Bundle.main.url(forResource: "index", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
Attempt 3:
let htmlPath = Bundle.main.path(forResource: "index", ofType: "HTML")
let folderPath = Bundle.main.bundlePath
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)
do {
let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlString as String, baseURL: baseUrl)
} catch {
// catch error
}
The solutions attempted above were suggested from this post and this. All the above returns the following result: