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

时间:2019-11-15 13:46:11

标签: swift wkwebview swiftui wkwebviewconfiguration

我正在尝试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")显示selfArgument type 'ggWebView' does not conform to expected type 'WKScriptMessageHandler'处出错。

1 个答案:

答案 0 :(得分:0)

由于WKScriptMessageHandler要求实现它的对象继承自NSObject,因此最好创建一个单独的类ContentController来实现那些协议,而不是更改{{ 1}}。

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方法(WKScriptMessageHandler(这不是班级的最佳名称,因为它应该以大写字母开头))。您必须将func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)的类型从ggWebView更改为structure。我可以看到您已经添加了class方法,因此您只需要将类签名更新为:

userContentController(_:didReceive:)