从 html 字符串创建 URL (Swift)
我必须在iOS应用中加载一个小的HTML零件。 我可以将其保存在文件中并使用FilePath加载URL,
URL(fileURLWithPath: Bundle.main.path(forResource: fileName, ofType: "HTML")
但是我的HTML具有变量,因此我需要动态。 因此,我想从HTML作为字符串创建一个URL。
let htmlString = """
<div>.....</div>
"""
我尝试了不同的初始评估器,例如URL(字符串:HTMLString)或URL(数据:data:htmlstring.utf8)),但它们不起作用。 无论如何我可以实现这一目标吗?
*对使用wkwebview的直接方法不感兴趣。
I have to load an small HTML part in my iOS app.
I could save it in a file and load the URL using the filePath
URL(fileURLWithPath: Bundle.main.path(forResource: fileName, ofType: "HTML")
But my HTML has a variable so I need it to be dynamic.
So I want to create an URL from the HTML as a string.
let htmlString = """
<div>.....</div>
"""
I tried different initialisers like URL(string: htmlString) or URL(data: Data(htmlString.utf8)) but they don't work.
Anyway I can achieve this ?
*Not interested in using the direct method of WKWebView.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想将网页内容从内存加载到
WKWebView
中,请创建 Web 视图并调用load(_:mimeType:characterEncodingName:baseURL:)
从内存加载内容。这就是该方法的用途。否则,您需要将内容保存到本地文件(可能在应用程序的缓存目录中)构建该文件的文件 URL,然后使用
loadFileURL(_:allowingReadAccessTo:)
loadFileURL(_:allowingReadAccessTo:)If you want to load web content into a
WKWebView
from memory, create the web view and callload(_:mimeType:characterEncodingName:baseURL:)
to load the content from memory. That's what that method is for.Otherwise you will need to save your content to a local file, (probably in your app's caches directory) build a file URL to that file, and then load that into your web view using
loadFileURL(_:allowingReadAccessTo:)