WebView loadHTMLString:baseURL:不加载css

时间:2013-10-02 09:38:56

标签: ios css webview

我有这个代码:

NSURL *mainBundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:htmlFile baseURL:mainBundleURL];

我知道htmlFile是正确的。里面有:

<link rel="stylesheet" type="text/css" href="stylesheet.css">

我也知道mainBundle中的stylesheet.css。我检查了project.app内容。

问题是webview是空的。但是如果我使用base Url作为nil:

[webView loadHTMLString:htmlFile baseURL:nil];

webview显示内容,但没有css文件。

我不知道为什么这不起作用。提前谢谢。

3 个答案:

答案 0 :(得分:1)

我使用resourceURL属性

解决了这个问题
NSURL *baseURL = [[NSBundle mainBundle] resourceURL];

然后[webView loadHTMLString:htmlFile baseURL:baseURL];

-Sal

答案 1 :(得分:1)

大多数示例都引用baseUrl: nil但是为了访问CSS文件,您需要引用该包,以便<link rel="stylesheet" ...可以访问该文件。

这是我在Swift 3中的解决方案:

let baseUrl : URL = Bundle.main.resourceURL! as URL
let htmlFile = Bundle.main.path(forResource: "*html file name*", ofType: "html")
let htmlString = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(htmlString!, baseURL: baseUrl) 

归功于萨尔的答案,指出了这一点。

答案 2 :(得分:0)

Perhabs shouldStartLoadWithRequest方法会阻止您的请求。试试这个:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.absoluteString hasPrefix:@"file"]) {return YES;}

    //deal with the request
}
相关问题