Question

I've tried almost every way of loading an html file into an UIWebView that has images and resouces in the main bundle. The web page always loads but I can never get the images to show up.

NSString *html = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSString *htmldata = [NSString stringWithContentsOfFile:html encoding:NSUTF8StringEncoding error:nil];
NSString *path = [[NSBundle mainBundle] bundlePath];

[webView loadHTMLString:htmldata baseURL:[NSURL URLWithString:path]];

the HTML code has css:

background: url('image.png')

I've also assured that the file exists in the bundle when the app is run using other methods, but still no luck. Anyone see what's wrong with my code???

Was it helpful?

Solution

Instead of loading the HTML directly with loadHTMLString, you can have the web view do the work of loading the HTML from the bundled file. That way it should know where the HTML came from to resolve relative links.

Ex:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]];
[webview loadRequest:[NSURLRequest requestWithURL:url]];

I haven't tested the above, you may need the inDirectory clause of the pathForResource method. Good luck!

OTHER TIPS

This is an old post, but I think a way to make this work is to change the following line:

[webView loadHTMLString:htmldata baseURL:[NSURL URLWithString:path]];

to:

[webView loadHTMLString:htmldata baseURL:[NSURL fileURLWithPath:path]];

The method in the comment and jimbojw's answer works too, but in my case htmldata is not retrieved from a file, but instead is in memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top