参数类型不符合预期类型 'WKScriptMessageHandler'

Argument Type does not conform to expected type 'WKScriptMessageHandler'

我正在尝试 Swift 和 Javascript 与 SwiftUI 接口的双向集成。
这是将 WebKit 与 SwiftUI.

连接
import SwiftUI
import WebKit

struct ggWebView : UIViewRepresentable {

    let filePath: String

    func makeUIView(context: Context) -> WKWebView  {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.configuration.userContentController.add(self, name: "jsHandler")
        let bundleURL = Bundle.main.resourceURL!.absoluteURL
        let html = bundleURL.appendingPathComponent(filePath)
        uiView.loadFileURL(html, allowingReadAccessTo:bundleURL)
    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "jsHandler"{
            print(message.body)
        }
    }
}

userContentController.add(self, name: "jsHandler")self 处显示错误 Argument type 'ggWebView' does not conform to expected type 'WKScriptMessageHandler'

因为 WKScriptMessageHandler 要求实现它的对象继承自 NSObject 最好创建一个单独的 class ContentController 来实现这些协议,而不是更改 GgWebView 的类型。

import SwiftUI
import WebKit

struct GgWebView: UIViewRepresentable {

    let filePath: String
    let contentController = ContentController()

    func makeUIView(context: Context) -> WKWebView  {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.configuration.userContentController.add(contentController, name: "jsHandler")
        let bundleURL = Bundle.main.resourceURL!.absoluteURL
        let html = bundleURL.appendingPathComponent(filePath)
        uiView.loadFileURL(html, allowingReadAccessTo:bundleURL)
    }

    class ContentController: NSObject, WKScriptMessageHandler {
        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            if message.name == "jsHandler"{
                print(message.body)
            }
        }
    }
}

您必须确认 ggWebView(顺便说一句,这不是 class 的最佳名称,因为它应该以大写字母开头)到 WKScriptMessageHandler 协议并实施 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) 方法。您必须将 ggWebView 的类型从 structure 更改为 class。我可以看到你已经添加了一个 userContentController(_:didReceive:) 方法,所以你只需要将你的 class 签名更新为:

class ggWebView: UIViewRepresentable, WKScriptMessageHandler {