Matt Palmerlee Matt Palmerlee - 1 year ago 334
iOS Question

Load resources from relative path using local html in uiwebview

I have a very simple iOS app with a uiwebview loading a very simple test page (test.html):

<img src="img/myimage.png" />

I load this test.html file into my web view:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:html baseURL:baseUrl];

This works fine if I reference the image without the relative path and put the referenced image in the root path under Targets -> Copy Bundle Resources within XCode, however I can't get it to work with the relative path as shown in my html file. There must be a way to do this, I have lots of images, css, javascript files that I want to load into the webview and I would like not to have to have everything in the root and have to change all the references in my web app.

Answer Source

This is how to load/use a local html with relative references.

  1. Drag the resource into your xcode project (I dragged a folder named www from my finder window), you will get two options "create groups for any added folders" and "create folders references for any added folders".
  2. Select the "create folder references.." option.
  3. Use the below given code. It should work like a charm.

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

Now all your relative links(like img/.gif, js/.js) in the html should get resolved.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download