6

我有一个这样构造的 HTML 页面:

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

  </body>
</html>

它存储在我的文档目录中:

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

我还将 style.css 存储在文档目录中:

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

但是现在,当我尝试使用以下方法将 html 加载到我的 webview 中时:

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];

未加载 css,当我使用 NSURLProtocol 拦截对样式表的请求时,我可以看到请求是错误的。它试图请求:

文件:///style.css

而不是完整的 baseURL。现在我可以通过删除html文件中/style.css前面的/来解决这个问题。但是有没有一种简单的方法可以在不修改 html 的情况下在本机代码中解决这个问题?

4

2 回答 2

12

通过以下方式生成路径和基本 url:

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

关于这个主题的一个很棒的博客:

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

关于该主题的 SO QA

UIWebView 和本地 css 文件

于 2012-06-28T06:26:16.583 回答
2

删除斜线是唯一的解决方案

于 2012-07-23T09:27:50.007 回答