Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView baseURL and absolute path

I have an HTML page that is constructed like this:

<html>
  <head>
    <link rel="stylesheet" href="/style.css" />
  </head>
  <body>

  </body>
</html>

It is stored in my documents directory:

/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/12345-ID/Documents/mysite/index.html

I have also stored the style.css in the documents directory:

/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/12345-ID/Documents/mysite/style.css

But now, when I try to load the html into my webview using this:

NSURL *test = [NSURL URLWithString:@"file:///Users/username/Library/Application Support/iPhone%20Simulator/5.1/Applications/12345-ID/Documents/mysite/"]
[myWebView loadHTMLString:<the content retrieved from index.html> baseURL:test];

The css is not loaded, when I intercept the request to the stylesheet with a NSURLProtocol I can see the request is wrong. It is trying to request:

file:///style.css

instead of the full baseURL. Now I can solve this by removing the / in front of /style.css in the html file. But is there an easy way to resolve this in native code without modifying the html?

like image 583
Thizzer Avatar asked Jun 27 '12 21:06

Thizzer


2 Answers

Generate your path and base url the following way:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

A great blog on the subject:

http://iphoneincubator.com/blog/windows-views/uiwebview-revisited

A SO QA on the subject

UIWebView and local css file

like image 55
trumpetlicks Avatar answered Nov 14 '22 23:11

trumpetlicks


Removing the slash was the only solution

like image 28
Thizzer Avatar answered Nov 15 '22 01:11

Thizzer