2

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: enter image description here

Koh
  • 2,687
  • 1
  • 22
  • 62

1 Answers1

1

The problem is that this statement is wrong:

My folder structure:

- web
  -- images
     -- test.png
  -- index.html

That may be what the Project navigator looks like, but those yellow things in the Project navigator ("web", "images") are not folders. They are just organizational devices for the Project navigator itself (groups), to help you find your stuff. In the built app, your resources are being loaded flat into the app bundle, so that test.png and index.html are at the same level together, namely, the top level of the bundle.

If what you really wanted was in fact a "web" folder with that structure inside your app bundle, then you needed this to be a folder reference, which is a very different thing.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    See for example https://stackoverflow.com/a/48758433/341994. Your code will need to change considerably if you make a folder reference, because _index.html_ will not be at the top level any more either. – matt Oct 21 '20 at 14:53