Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link to resources inside WebView - iPhone

I have a webview in my iPhone application, and I also have some html files inside my Resources folder. When my app loads, I load in a page from my resources into my webview. But , I need to make links inside my webview that point to some other resources (For example, images, or other html files). Just doing a relative link doesn't work:

<a href="OtherPage.html">Doesn't work</a>
like image 807
Isaac Waller Avatar asked Jan 26 '09 01:01

Isaac Waller


2 Answers

Apparently there's a bit of a gotcha according to the iPhone SDK Release Notes for iPhone OS 3.0:

Issue: UIWebView can't load local resources in apps built against 3.0.

When using [UIWebView loadHTMLString:baseURL:], the HTML string should not refer to local resources with the file:// scheme. Instead, pass in NULL or a file:// URL for baseURL:, or include the resources directly in the HTML with <style> and <script> tags.

Fair enough. But passing in a standard-issue file:// URL for baseURL doesn't quite work. However ... it turns out that, if you change / to // and spaces to %20, you will be set! (Using %20 makes a lot of sense, but the double-slash part caught me by surprise.)

Let's say you already have NSString *markup set up. Here's all you do. (I've wrapped the code here for readability. You may wish to refactor/adjust to taste.)

 NSString *resourcePath = [[[[NSBundle mainBundle] resourcePath]
     stringByReplacingOccurrencesOfString:@"/" withString:@"//"]
     stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
 [webView loadHTMLString:markup baseURL:[NSURL URLWithString:
     [NSString stringWithFormat:@"file:/%@//", resourcePath]]];

So long as your CSS, JavaScript and images are referred to by filename alone, this should do the trick in iPhone OS 3.0 where loadHTMLString:baseURL: is concerned!

like image 126
Joe D'Andrea Avatar answered Oct 09 '22 13:10

Joe D'Andrea


When you load those resources, you need to set the base URL. You can do this using the method:

- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL

...where baseURL would be the file URL of your resources folder.

like image 35
August Avatar answered Oct 09 '22 13:10

August