如何将 HTML 代码加载到 Swift 上的 WebView

How can I load HTML Code to WebView on Swift

我在 Whosebug 上搜索了如何在 swift 上实现我的 webview 以显示 html 代码并且已经找到了一些东西。

但是没用。我的问题是我没有收到错误。 我的应用程序应该启动并在 webkit 中打开一个视频,但没有任何反应。它只显示一个空白页。 这是我的代码。我在控制台上收到一条消息,但不明白问题出在哪里。

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        let webView = WKWebView()
        webView.loadHTMLString("<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/0zrSJ6jhAY0\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>", baseURL: nil)
}}

我还上传了截图。也许我的 main.storyboard 做错了,但我不这么认为。 enter image description here

您应该在正文字符串前后添加 html 标记。试试下面的代码:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        webView.loadHTMLString("<!DOCTYPE html><html><body><iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/0zrSJ6jhAY0\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></body></html>", baseURL: nil)
    }


}

在 UIWebView 中:-

let webView = UIWebView()
webView.loadHTMLString("<!DOCTYPE html><html><head>Loading HTML</head><body><p>Hello!`</p></body></html>", baseURL: nil)`

从 2020 年 4 月开始,任何应用都不允许使用 UIWebView。因此,我们需要为此使用 WKWebView。

现在这是 WKWebView 的代码:

let webView = WKWebView()
webView.loadHTMLString("<!DOCTYPE html><html><head>Loading HTML</head><body><p>Hello!`</p></body></html>", baseURL: nil)`