Using HTML and Local Images Within UIWebView

Jasarien picture Jasarien · Apr 14, 2009 · Viewed 116.2k times · Source

I have a UIWebView in my app which I want to use to display an image which will link to another url.

I'm using

<img src="image.jpg" /> to load the image.

The problem is that the image doesn't load (ie. it can't be found) even though it's added as a resource in my project and is copied into the bundle.

I've tried using NSBundle to get the full path of the image and using that and it still doesn't show up in the web view.

Any ideas?

Answer

Adam Alexander picture Adam Alexander · Apr 14, 2009

Using relative paths or file: paths to refer to images does not work with UIWebView. Instead you have to load the HTML into the view with the correct baseURL:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

You can then refer to your images like this:

<img src="myimage.png">

(from uiwebview revisited)