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?
pathForResource:ofType:
fromNSBundle
and then reference usingfile://<local_uri>
in your own HTML. For example, forjquery-2.1.1.min.js
, I use:NSString *jQueryFile = [[NSBundle mainBundle] pathForResource:@"jquery-2.1.1.min" ofType:@"js"]; NSString *jQueryUri = [@"file://" stringByAppendingString:jQueryFile];
and then I simply add it to my HTML:NSString *html = [NSString stringWithFormat:@"<some_html><script type=\"text/javascript\" src=\"%@\"></script></some_html>", jQueryUri];
. Finally:[myWebView loadHTMLString:html baseURL:nil];
– Alejandro Iván