创建 webView
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
configuration.userContentController = WKUserContentController()
let statusHeight = UIApplication.shared.statusBarFrame.height
var webView = WKWebView(frame: view.bounds, configuration: configuration)
// 允许右滑返回
webView.allowsBackForwardNavigationGestures = true
webView.navigationDelegate = self
view.addSubView(webView)
// 加载本地html文件
let HTML = try! String(contentsOfFile: Bundle.main.path(forResource: "index", ofType: "html")!, encoding: String.Encoding.utf8)
webView.loadHTMLString(HTML, baseURL: nil)
// 加载 url
webView.load(URLRequest(url: URL(string: "https://m.xxx.com")!))
webview 与 swift 交互
h5 调用 swift 方法:如 AppFunc
// swift 提供给 h5 调用方法
configuration.userContentController.add(self, name: "AppFunc")
// 接受 h5 调用
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.name)
print(message.body)
}
// h5 调用 swift 方案
window.webkit.messageHandlers.AppFunc.postMessage("这是传个 Swift 的")
swift 注入代码到 h5 页面
webView.evaluateJavaScript("sayHello('WebView你好!')") { (result, err) in
print(result ?? "", err ?? "")
}
开启 webView 里的页面可以右滑返回上一个web页面
webView.allowsBackForwardNavigationGestures = true
此时,如果 webview 的控制器有导航栏,那么就会出现手势冲突问题
解决办法:
webView 的属性 canGoBack :A Boolean value indicating whether there is a back item in the back-forward list that can be navigated to. 解释为当前 webview 里的返回列表是否有后退项。通过 KVO 监听该属性,开启和关闭导航栏的手势就可以了
// KVO 监听 canGoBack,注意只有跳转到第二个页面,和返回到第一个页面时,该属性值才会变化
webView.addObserver(self, forKeyPath: "canGoBack", options: .new, context: nil)
open override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
guard let theKeyPath = keyPath, object as? WKWebView == webView else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if theKeyPath == "canGoBack" {
if let newValue = change?[NSKeyValueChangeKey.newKey]{
let newV = newValue as! Bool
if newV == true{
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false;
}else{
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
}
}
}
}
// 别忘了移除观察者
deinit {
webView.removeObserver(self, forKeyPath: canGoBackKeyPath, context: nil)
}
网友评论