WKWebView与JS交互
//WKWebView 中。JS调用OC方法
重写WKScriptMessageHandler避免与JS交互时内存泄漏。
class WeakScriptMessageDelegate: NSObject, WKScriptMessageHandler {
weak var scriptDelegate: WKScriptMessageHandler?
init(_ scriptDelegate: WKScriptMessageHandler) {
self.scriptDelegate = scriptDelegate
super.init()
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
scriptDelegate?.userContentController(userContentController, didReceive: message)
//print("传来的数据为", message.body)
}
deinit {
print("WeakScriptMessageDelegate is deinit")
}
}
创建WKWebView并添加与JS交互的事件
lazy var webView: WKWebView = {
///偏好设置
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
configuration.selectionGranularity = WKSelectionGranularity.character
configuration.userContentController = WKUserContentController()
// 给webview与swift交互起名字,webview给swift发消息的时候会用到
//invokePage
configuration.userContentController.add(WeakScriptMessageDelegate(self), name: "invokePage")
configuration.userContentController.add(WeakScriptMessageDelegate(self), name: "backPage")
var webView = WKWebView(frame: CGRect(x: 0,
y: 0,
width: UIScreen.main.bounds.width,
height: UIScreen.main.bounds.height),
configuration: configuration)
// 让webview翻动有回弹效果
webView.scrollView.bounces = false
// 只允许webview上下滚动
webView.scrollView.alwaysBounceVertical = true
webView.navigationDelegate = self
return webView
}()
设置JS交互代理
extension YLJIntegralinvitationVC: WKScriptMessageHandler{
///接收js调用方法
func userContentController(_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage) {
///在控制台中打印html中console.log的内容,方便调试
let body = message.body
if message.name == "logger" {
print("JS log:(body)")
//EWToast.showBottomWithText(text: "JS log:(body)")
return
}
///
switch message.name {
case "invokePage":
invokePage(string: message.body as! String)
case "backPage":
backPage(string: message.body as! String)
default:
break
}
}
}
//WKWebView. OC 调用JS方法
直接使用系统方法即可
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;