gpt4 book ai didi

javascript - 如何使用 LoadHTMLString 方法在 WebView 中加载大型 HTML 字符串?

转载 作者:行者123 更新时间:2023-11-30 12:33:42 25 4
gpt4 key购买 nike

我必须使用 UIWebView 的“LoadHTMLString”方法将 html 字符串加载到 UIWebView。

请找到下面的代码。

[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 上?或者任何人都可以告诉我这段代码出了什么问题。

最佳答案

你只需要创建一个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]];

编辑:

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

我认为问题是因为你在运行时加载了这个字符串。

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

因此这里可能存在问题的是 html 字符串中的一些函数在加载之前使用了一些文件或帮助。这就是运行时 html 创建和加载不起作用的原因。

如果我有误导,请多多澄清。

不过,您可以在 html 文件中设置运行时值。

Exmaple.html

<!DOCTYPE html>
<html>
<head>
</head>

<body>

#latitude#

#longitude#

</body>
<html>

参见上面的文件,您可以在该文件中添加 #latitude##longitude# 标记。并在运行时替换它。就像下面的代码。

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>];

关于javascript - 如何使用 LoadHTMLString 方法在 WebView 中加载大型 HTML 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26799493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com