objective-cuiwebviewnsbundlemainbundle

UIWebView local Resource main bundle html file


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???


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!