Using HTML and Local Images Within UIWebView Using HTML and Local Images Within UIWebView ios ios

Using HTML and Local Images Within UIWebView


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)


Use this:

[webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];


I just ran into this problem too. In my case, I was dealing with some images that were not localized and others that were--in multiple languages. A base URL didn't get the images inside localized folders for me. I solved this by doing the following:

// make sure you have the image name and extension (for demo purposes, I'm using "myImage" and "png" for the file "myImage.png", which may or may not be localized)NSString *imageFileName = @"myImage";NSString *imageFileExtension = @"png";// load the path of the image in the main bundle (this gets the full local path to the image you need, including if it is localized and if you have a @2x version)NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageFileName ofType:imageFileExtension];// generate the html tag for the image (don't forget to use file:// for local paths)NSString *imgHTMLTag = [NSString stringWithFormat:@"<img src=\"file://%@\" />", imagePath];

Then, use imgHTMLTag in your UIWebView HTML code when you load the contents.

I hope this helps anyone who ran into the same problem.