问题
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?
回答1:
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
回答2:
Removing the slash was the only solution
来源:https://stackoverflow.com/questions/11235207/uiwebview-baseurl-and-absolute-path