1.H5调原生方法
利用 WKUserContentController来管理 JavaScript 与 swift 的通信
add(:name:) 方法将当前类(必须实现 WKScriptMessageHandler 协议)注册为一个消息处理器。
"callbackHandler" 是 JS 调用 Native 时使用的名称。
在 JS 中可以这样调用:window.webkit.messageHandlers.callbackHandler.postMessage("method")
当 JS 调用这个方法后,会触发 userContentController(:didReceive:) 回调函数。
注册
let contentController = WKUserContentController()
contentController.add(self, name: "callbackHandler")
let config = WKWebViewConfiguration()
config.userContentController = contentController
config.preferences.javaScriptCanOpenWindowsAutomatically = true
if #available(iOS 14.0, *) {
let preferences = WKWebpagePreferences()
preferences.allowsContentJavaScript = true
config.defaultWebpagePreferences = preferences
}else {
config.preferences.javaScriptEnabled = true
}
webView = WKWebView(frame: .zero, configuration: config)
webView.backgroundColor = .white
webView.isOpaque = false
需要实现 WKScriptMessageHandler代理处JavaScript发送的消息 , js 需要调原生
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "callbackHandler", let body = message.body as? String{
// DLog("===收到 JavaScript 消息字符串:\(body)")
// showAlert()
handMessBodyType(bodyStr: body)
}else if message.name == "callbackHandler", let body = message.body as? [String:Any]{
// DLog("===收到 JavaScript 消息字典:\(body)")
if let action = body["action"] as? String {
if let content = body["data"] as? String {
handMessBodyType(bodyStr: action, data: content)
}
if let dict = body["data"] as? Dictionary<String,Any> {
handMessBodyType(bodyStr: action, data: nil, dataDict: dict)
}
}
}
}
处理原生调用 js 方法
getToken 是于H5端双方约定的方法名
webView.evaluateJavaScript("window.getToken('\(token)')") { (result, error) in
DLog("===向网页传值:\(String(describing: result))=====\(error?.localizedDescription ?? "")")
if let error = error {
DLog("JavaScript 执行失败: \(error.localizedDescription)")
} else {
DLog("向网页传值成功")
}
}
以上,就是在处理swift原生与H5交互的逻辑功能,来帮助需要的人,赠人玫瑰,手有余香,希望我能帮助到还在写代码的你!