UIWebView baseURL和绝对路径

Thy*_*hys 6 html uiwebview base-url

我有一个HTML页面,构造如下:

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

  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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

/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/12345-ID/Documents/mysite/index.html
Run Code Online (Sandbox Code Playgroud)

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

/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/12345-ID/Documents/mysite/style.css
Run Code Online (Sandbox Code Playgroud)

但现在,当我尝试使用以下方法将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];
Run Code Online (Sandbox Code Playgroud)

没有加载css,当我用NSURLProtocol拦截样式表的请求时,我可以看到请求是错误的.它试图要求:

文件:///style.css

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

tru*_*cks 12

以下列方式生成您的路径和基本URL:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
Run Code Online (Sandbox Code Playgroud)

关于这个主题的精彩博客:

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

关于这个问题的SO QA

UIWebView和本地css文件


Thy*_*hys 2

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