从 js 调用 swift 函数

Call swift function from js

请告诉我我应该如何实现swift中的功能以便在js中调用。 现在 js 调用函数 mobile.preScreenerFinished(orderId, account.email, "ACCEPTED");并为 android.

调用 kotlin 函数

这是我的代码:

import WebKit

protocol PreScreenerUIViewDelegate: class {
    func preScreenerFinished(_ orderId: Int, _ email: String, _ status: String)
}

class PreScreenerUIView: WKWebView, WKScriptMessageHandler {
    
    var delegate: PreScreenerUIViewDelegate!
        
    init(frame: CGRect, orderId: Int) {
        let url = "\(Session.instance.url)/mobile-prescreener"
        let config = WKWebViewConfiguration()
        let contentController = WKUserContentController();
    
        config.userContentController = contentController

        super.init(frame: frame, configuration: config)
    
        contentController.add(self, name: "mobile")
    
        self.load(URLRequest(url: URL(string: url)!))
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let dictionary = message.body as? [String: Any]
        guard
            let orderId = dictionary?["orderId"] as? Int,
            let email = dictionary?["email"] as? String,
            let status = dictionary?["status"] as? String
        else { return }
        
        delegate?.preScreenerFinished(orderId, email, status)
    }
}

您需要更改 Javascript(或注入 Javascript 代码)以调用 postMessage() 函数。由于您只能传递一个参数,因此您可以编写 JSON:

window.webkit.messageHandlers.mobile.postMessage({
    "orderId": orderId,
    "email": account.email,
    "status": "ACCEPTED"
});

这样你就可以像字典一样处理 body 属性 of WKScriptMessage,在 Swift:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    let dictionary = message.body as? [String: Any]
    guard
        let orderId = dictionary?["orderId"] as? Int,
        let email = dictionary?["email"] as? String,
        let status = dictionary?["status"] as? String
    else { return }
    
    delegate?.preScreenerFinished(orderId, email, status)
}