从 html 字符串创建 URL (Swift)

发布于 2025-01-19 08:00:38 字数 422 浏览 3 评论 0原文

我必须在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

<逆流佳人身旁 2025-01-26 08:00:38

如果您想将网页内容从内存加载到 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 call load(_: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:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文