如何使用LoadHTMLString方法在WebView中加载大型HTMLstring?

我必须使用UIWebView的“LoadHTMLString”方法将一个htmlstring加载到UIWebView上。

请find下面的代码。

[wv loadHTMLString:[NSString stringWithFormat:@"<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\"><meta charset=\"utf-8\"><title>Traffic layer</title><style>html, body, #map-canvas {height: 100%%;margin: 0px;padding: 0px}</style><script src=\"https://maps.googleapis.com/maps/api/js?v=3.exp\"></script><script>function initialize() {var myLatlng = new google.maps.LatLng(34.04924594193164, -118.24104309082031);var mapOptions = {zoom: 13,center: myLatlng}var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptiotrafficLayer.setMap(map);}google.maps.event.addDomListener(window, 'load', initialize);</script></head><body><div id=\"map-canvas\"></div></body></html>"] baseURL:nil] 

当我加载这个,我的webview是空的,它不显示任何东西。

当我把这个代码放入扩展名为'html'的文件中并加载到webview时,它工作正常。

任何人可以帮我把这个加载到WebView? 或者,任何人都可以让我知道这段代码出了什么问题。

你只需要创build一个HTML文件,并把所有的HTML内容,并使用代码来加载该文件

 [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"filename" ofType:@"html"] isDirectory:NO]]]; 

并使用这也

 NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"html"]; NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; [self.webView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]]; 

编辑:

我被忽视了,你已经提到加载文件工作完美。

我想问题是因为你在运行时加载这个string。

我们都知道,当我们使用html和css文件时,我们需要在“Copy Bundle Resources”中添加这些文件。 这样在运行时加载html页面时就可以使用了。

所以这里可能是问题的一些function,在加载之前,htmlstring使用一些文件或援助。 所以这就是为什么运行时的HTML创build和加载不起作用。

如果我误导了我,怎么能清楚我呢?

尽pipe你可以在html文件中设置运行时间值。

Exmaple.html

 <!DOCTYPE html> <html> <head> </head> <body> #latitude# #longitude# </body> <html> 

见上面的文件,你可以在文件中添加#latitude##longitude#这样的标记。 并在运行时replace它。 像下面的代码。

 NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"html"]; NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; html = [html stringByReplacingOccurrencesOfString:@"#latitude#" withString:<LATITUDE-VALUE>]; html = [html stringByReplacingOccurrencesOfString:@"#longitude#" withString:<LONGITUDE-VALUE>]; 

两天后,长期睡眠,我想出了这个。

迅速

 let path = NSBundle.mainBundle().pathForResource("public_html/index", ofType: "html") var html = try? NSString(contentsOfFile: path! as String, encoding: NSUTF8StringEncoding) html = html?.stringByReplacingOccurrencesOfString("#latitude#", withString:"<p class=\"text-center\">Center aligned text.</p><blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p></blockquote>") webView.loadHTMLString(html as! String, baseURL: NSURL(fileReferenceLiteral: "public_html")) 

首先,我的HTML代码在我的项目(public_html / index.html)中。 此代码加载HTML,将其转换,replace标签“#latitude#”,并使用该目录加载HTML(用于加载JS等)。