iPhone dev: load a file from resource folder

thomax picture thomax · Mar 25, 2010 · Viewed 26.8k times · Source

I'm writing an iPhone app with a UIWebView which should display various html files I have in the app resource folder. In xcode my project overview, these html files are displayed like this:

dirA
|---> index.html 
|---> a1.html
|---> a2.html
|---> my.css
|---> dirB
      |---> b1.html
      |---> b2.html
|---> dirC
      |---> c1.html
      |---> c2.html

These resources where added to the project as such:

  • Checked "Copy items into destination groups folder (if needed)".
  • Reference type: Default.
  • Text encoding: Unicode (utf-8).
  • Recursively create groups for any added folders.

The links in my html are relative, meaning they look like this:

<a href="a1.html">a1</a>
<a href="a2.html">a2</a>
<a href="dirB/b2.html">b2</a>
<a href="dirC/c1.html">c1</a>

In order to display the index.html when the app starts up, I use the following code:

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

This works fine. Following links from the index file also works fine, as long as the html files requested are directly under dirA. If the link followed points to a file in a sub-directory, then didFailLoadWithError will catch the situation and report that the requested file does not exist.

Also,

[webView loadHtmlString:myHtml];

cannot be part of the solution, as I need back and forward buttons to work in my web view.

So the question is: How can I follow a relative link to an html file in a sub directory within my resources?

I've been all over stackoverflow and the rest of the tubes for the past few days trying to figure this one out, but nowhere have I come across the solution to this exact problem. Any insight at all would be very, very much appreciated!

EDIT: Yoohoo! I figured it out! What joy! Here is what I did:

  1. Imported my resources anew, choosing "Create folder references for any added folders" instead of "Recursively create groups for any added folders."
  2. Specified the root directory for resource, like so: NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"dirA"];

Answer

zaph picture zaph · Mar 26, 2010

To create folders in the app bundle drag the folder to Xcode and select the radio button: "Create Folder References for any added folders".