swift之与h5之间的交互(二)

很多小伙伴表示有场景需要给h5端进行交互方法相互调用传值,今天就给大家简单的介绍下:

首先咋们iOS端先搭建好自己的环境,不废话上代码

一.h5调用iOS端

1.先搭建wkwebview,布局的代码省略,遵守协议WKScriptMessageHandler

let webView: WKWebView = {
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        let config = WKWebViewConfiguration()
        let controller = WKUserContentController()
        config.userContentController = controller
        config.preferences = preferences
        let webView = WKWebView(frame: .zero, configuration: config)
        webView.scrollView.showsVerticalScrollIndicator = false
        webView.scrollView.showsHorizontalScrollIndicator = false
        webView.scrollView.bounces = false
        webView.navigationDelegate = self
        if #available(iOS 11.0, *) {
            webView.scrollView.contentInsetAdjustmentBehavior = .never
        }
        return webView
    }()

2.提前与h5商定好字段,然后设置监听,这里以"toBackApp"为例,分别放在viewWillAppear和viewWillDisappear方法里

//返回
webView.configuration.userContentController.add(self, name: "toBackApp")
webView.configuration.userContentController.removeScriptMessageHandler(forName: "toBackApp")

3.监听方法调用及解析

//MARK: 接收方法
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        switch message.name {
        case "toBackApp":
            if webView.canGoBack {
                webView.goBack()
            } else {
                self.navigationController?.popViewController()
            }
        default:
            break
        }
    }
//如果是h5传参过来则用message.body去接收,然后再去解析

  

二.iOS端调用h5

//MARK: js调用方法,如果涉及传参则在refreshH5('传参数据')
    @objc func didBecomeActiveNotificationClick() {
        let inputJS = "JavaCallJs.refreshH5(\"\")"
        webView.evaluateJavaScript(inputJS) { (response, error) in
            print(inputJS + " \(response.debugDescription) ")
        }
        
    }
//注意error是否为nil,不为nil则调用失败,需要与前端联调

 

posted @ 2024-03-07 10:53  哇哈爽  阅读(150)  评论(0编辑  收藏  举报