参数类型不符合预期类型“WKScriptMessageHandler”

Lon*_*aso 3 swift wkwebview wkwebviewconfiguration swiftui

我正在尝试在 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

baz*_*l87 8

由于WKScriptMessageHandler要求实现它的对象继承,NSObject所以最好创建一个单独的类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)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

class ggWebView: UIViewRepresentable, WKScriptMessageHandler {
Run Code Online (Sandbox Code Playgroud)