我有一个像这样构建的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];
当我使用NSURLProtocol拦截样式表请求时,发现CSS未加载,可以看到请求是错误的。它试图请求:
file:///style.css
而不是完整的基本URL。现在,我可以通过在HTML文件中删除/style.css前面的/来解决这个问题。但是,在不修改HTML的情况下,是否有一种简单的方法在本地代码中解决这个问题?
NSBundle
中的pathForResource:ofType:
获取本地 URI,然后在自己的 HTML 中引用file://<local_uri>
。例如,对于jquery-2.1.1.min.js
,我使用:NSString *jQueryFile = [[NSBundle mainBundle] pathForResource:@"jquery-2.1.1.min" ofType:@"js"]; NSString *jQueryUri = [@"file://" stringByAppendingString:jQueryFile];
然后我只需将其添加到我的 HTML 中:NSString *html = [NSString stringWithFormat:@"<some_html><script type=\"text/javascript\" src=\"%@\"></script></some_html>", jQueryUri];
。最后:[myWebView loadHTMLString:html baseURL:nil];
- Alejandro Iván