UIWebview未获取链接的CSS资源

时间:2013-03-11 12:45:34

标签: ios uiwebview

我正在尝试将本地html内容加载到uiwebview中。我已经准备好了html内容,我正在通过机制向内容添加一个在线css文件的引用,如下面的代码所示。但是,我面临的问题是当我加载webview时,没有样式。此外,我在Charles Proxy中验证,没有传出的调用将iphone.css文件提取到我的基本服务器。理想情况下,在加载html页面时,uiwebview应该获取所有引用的资源,但由于某些原因我不知道,它不会获取css文件。

如果我的代码存在某些问题,请检查并告诉我,我无法在此处识别出来?

NSString* htmlString = @"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"he\" lang=\"he\"><head><link type=\"text/css\" href=\"http://<base_server>/resources/iphone.css\" /><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body>%@</body></html>";


        UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        NSLog(@"%@",[NSString stringWithFormat:htmlString,entry.body]);
        [webview loadHTMLString:[NSString stringWithFormat:htmlString,entry.body] baseURL:[NSURL URLWithString:@"http://<base_server>/"]];

        [self addSubview:webview];

1 个答案:

答案 0 :(得分:2)

很难判断HTML中是否存在任何拼写错误,并且该字符串中的所有双引号转义都在进行中。为什么不将HTML从字符串中拉出来并放入文件中,读取该文件并将内容放入正文中。该字符串中的标记可能存在错误。这样您就可以在单独的文件中更轻松地阅读它。

类似的东西:

NSError *error;
NSStringEncoding encoding;
NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource: @"Sample" 
                                                         ofType: @"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFilePath 
                                             usedEncoding:&encoding 
                                                    error:&error];

NSString *html = [NSString stringWithFormat:htmlString, entry.body];

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

[webview loadHTMLString:html baseURL:baseURL];