tags:

views:

68

answers:

1

After browsing quite a bit, I still can't figure this out. I've added a HTML page and its images directory into my project Resources group in Xcode (Copied them over).

When I try to load the webview with the following code, the text is displayed fine, but the images aren't loaded.

NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"index.html"];
NSString *htmlContent = [NSString stringWithContentsOfFile:path];
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[[tempWebView mainFrame] loadHTMLString:htmlContent baseURL:url];

Any help is much appreciated!

EDIT: Sorry about the delay, here's some basic html that failed.

<html>
    <body> 
        <img src="images/bg.png"></img> 
    </body>
</html>

And my edited code looks like this -

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

EDIT2: Just realized it was an issue with the path. Apparently <img src = "images/bg.png"> doesn't work, but if I copy bg.png to the root directory and say <img src = "bg.png"> everything works fine. I'm still not sure where I'm going wrong with this.

Thanks,
Teja.

+1  A: 

Consider doing the following:

  1. Instead of getting the resource path and stapling a subpath onto it yourself, ask the bundle to give you the correct path.
  2. Instead of handling a path at all, ask the bundle to give you the correct URL. (Requires Mac OS X 10.6 or later.)
  3. Instead of injecting HTML contents directly into the frame, ask the WebView to load the URL.

This reduces your code to two lines that, if the HTML code is correct, will work.

Peter Hosey
Actually, my initial implementation was like that. But, I saw one of the SO questions where someone was having the same problem, but fixed it by implementing it this way. I was wondering if it has something to do with the baseURL maybe.
Tejaswi Yerukalapudi
Tejaswi Yerukalapudi: Got a link to one of those questions?
Peter Hosey
Hmm, I can't seem to find it now, but I've edited my implementation to follow this. It appears that my issue is with using syntax that navigates to a sub-folders to grab the images in HTML. I kinda _get_ why this is happening, but I'm not sure what I can do to fix it, thanks for all your help again!
Tejaswi Yerukalapudi
Tejaswi Yerukalapudi: So if you look in the app bundle in your build folder, were you able to find the images directory copied there? (Also, there aren't supposed to be spaces around the equal sign in HTML.)
Peter Hosey
Oops, that was me just typing into SO directly, the original HTML doesn't have them. And, yes, the images were copied over.
Tejaswi Yerukalapudi
Tejaswi Yerukalapudi: Not what I asked. Did you find the images *directory* copied there?
Peter Hosey