Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load local images in a local HTML file within a UIWebView [duplicate]

I have tried a lot of other answers on here, but I can't seem to figure this one out. I have a local HTML file that embeds some local images.

My folder structure is:

assets
>html
>>*.html
>>*.html
>>*.html
>media
>>*.jpeg
>>*.jpeg
>>*.jpeg

and I request the images from the HTML with

<img src="../media/sjolyst.jpg" alt="Sjølyst"/>

My code for loading the web view pretty simple,

var path = NSBundle.mainBundle().pathForResource(htmlFileName, ofType: "html")!
let data: NSData = NSData(contentsOfFile:path)!
var html = NSString(data: data, encoding:NSUTF8StringEncoding)

detailWebView.loadHTMLString(html as! String, baseURL: NSBundle.mainBundle().bundleURL)

This seems to be the same as all the answers I've seen on SO. Still, it renders like this: :( How can I fix this issue?

like image 913
Oscar Apeland Avatar asked Mar 18 '15 09:03

Oscar Apeland


1 Answers

The problem is,

Your app can't figure out the where your resources are, and where your html is.

Why? Because your html and resources are added in bundle, which is scattered. You need to put all in single folder, so that your resources are accessible. According to your code

<img src="../media/sjolyst.jpg" alt="Sjølyst"/>

You are trying to fetch the image relatively, but in actual folder structure there is no ../media.

Solution simple.

  1. Delete all your html thing, I guess the folder.
  2. Re-add the HTML folder, see image enter image description here
  3. You should see a folder like image below

    enter image description here

You are now good to go.

By adding a folder mentioned in 2. creates a folder in bundle path, and put all the resource with correct folder structure inside it.

Hope this helps.

Cheers.

like image 135
iphonic Avatar answered Oct 17 '22 04:10

iphonic