1.创建wkwebview
import WebKit
lazy var webView: WKWebView = {
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
configuration.userContentController = WKUserContentController()
// 给webview与swift交互起一个名字:AppModel,webview给swift发消息的时候会用到
configuration.userContentController.add(self, name: "AppModel")
var webView = WKWebView(frame: self.view.frame, configuration: configuration)
// 让webview翻动有回弹效果
webView.scrollView.bounces = true
// 只允许webview上下滚动
webView.scrollView.alwaysBounceVertical = true
webView.navigationDelegate = self
return webView
}()
2.ViewController实现两个协议
两个协议分别是:WKNavigationDelegate WKScriptMessageHandler
WKNavigationDelegate:判断页面加载完成,只有在页面加载完成了,才能在swift中调webview中的js方法
WKScriptMessageHandler: 在webview中给swift发消息时要用到协议中的一个方法来接收
3.Swift调用WebView中的JS方法
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("sayHello('WebView你好!')") { (result, err) in
print(result, err)
}
}
4.拦截WebView中给Swift发消息
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.body)
}
详细代码
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {
lazy var webView: WKWebView = {
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
configuration.userContentController = WKUserContentController()
configuration.userContentController.add(self, name: "AppModel")
var webView = WKWebView(frame: self.view.frame, configuration: configuration)
webView.scrollView.bounces = true
webView.scrollView.alwaysBounceVertical = true
webView.navigationDelegate = self
return webView
}()
//加载前端webview
override func viewDidLoad() {
super.viewDidLoad()
self.urlStr = "这里是自己的网址/\(AntBoxSDKUtils.shared.antBoxURLParms)"
self.webView.load(URLRequest.init(url: URL.init(string: self.urlStr!)!))
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("sayHello('WebView你好!')") { (result, err) in
print(result, err)
}
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.body)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
本文参考:https://tomoya92.github.io/2018/07/05/swift-webview-javascript/ ,更多方法交流可以家魏鑫:lixiaowu1129,一起探讨iOS相关技术!
网友评论