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

3
  • Try changing img src='./images/test.png to img src='test.png'. Does it work now? If so, I can tell you what the problem is. Commented Oct 21, 2020 at 14:30
  • @matt Yes it worked. Attempt 2 and 3 works. What's the problem? Commented Oct 21, 2020 at 14:35
  • Explained it in an answer. Commented Oct 21, 2020 at 14:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

See for example 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.