WKWebView在Swift中的简单使用

2018-06-12  本文已影响0人  向日葵的夏天_summer

IOS8之后,苹果推出了WKWebView,用来替代UIWebView。WKWebView在性能,占用内存方面有了很大的提升。

0. 初始化WKWebView

let configuration = WKWebViewConfiguration()
configuration.userContentController = WKUserContentController()
webView = WKWebView(frame: view.bounds, configuration: configuration)
view.addSubview(webView)

let request = URLRequest(url: URL(fileURLWithPath: Bundle.main.path(forResource: "hello.html", ofType: nil)!))
webView.load(request)

webView.navigationDelegate = self
webView.uiDelegate = self

1. WKWebView 获取页面的title和进度条

通过用kvo的方法可以监听网页的加载进度, estimatedProgress

webView.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "title" { //title
        print(change?[NSKeyValueChangeKey(rawValue: "new")])
    } else if keyPath == "estimatedProgress" {   //进度条
        if let progress = change?[NSKeyValueChangeKey(rawValue: "new")] as? Float {
                print(progress)
        }
    }
}

2. WKWebView的navigationDelegate代理方法

//MARK:- 页面开始加载时候调用
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("页面开始加载")
} 

//MARK:- 当内容开始返回的时候调用
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    print("开始返回内容")
}

//MARK:- 页面加载完成之后调用
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("页面加载完成")
    // swift 调用js
    let js = "document.getElementsByName('input')[0].style.display = 'block';"
    webView.evaluateJavaScript(js) { (response, error) in
        print("response: \(response)")
        print("error: \(error)")
    }
}

//MARK:- 页面加载失败的时候调用
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    print("页面加载失败")
}

//MARK:- 在发送请求之前,决定是否跳转【可拦截URL做些操作什么的】
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
    if let urlString = navigationAction.request.url?.absoluteString {
        print(urlString)
    }
}

//MARK:- 在收到响应后 决定是否跳转
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void) {
    print(navigationResponse.response.url?.absoluteString)
    decisionHandler(WKNavigationResponsePolicy.allow)   //允许跳转
    //decisionHandler(WKNavigationResponsePolicy.cancel)  //不允许跳转
}

3.WKWebView的WKUIDelegate代理方法

//MARK:- 网页执行alert的时候调用
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
    
let alert = UIAlertController(title: "提示", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (_) in
        completionHandler()
    }))
    self.present(alert, animated: true, completion: nil)
}


//MARK:- js中的confirm确定框, 在completionHandler中用户选择返回
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Swift.Void) {
    print(message)
    let alert = UIAlertController(title: "提示", message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.default, handler: { (_) in
        completionHandler(true)
    }))
    self.present(alert, animated: true, completion: nil)
}


//MARK:- js中的prompt输入弹出框,completionHandler将输入信息返回
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Swift.Void) {
    print(prompt, defaultText)
    completionHandler(nil)
}

func webViewDidClose(_ webView: WKWebView) {
    print("webViewDidClose")
}

4. Swift调用JS代码

// swift 调用js
let js = "document.getElementsByName('input')[0].style.display = 'block';"
webView.evaluateJavaScript(js) { (response, error) in
        print("response: \(response)")
        print("error: \(error)")
    }

5. JS调用Swift代码

除了拦截URL之外, WKWebView中提供WKScriptMessageHandler这个协议来处理js调用swift代码,首先在js中定义一个方法,

window.webkit.messageHandlers.ClickMe.postMessage({"name": "wangyun", "age": 35})

然后在Swift中:

//添加js的方法ClickMe
webView.configuration.userContentController.add(self, name: "ClickMe")

遵守WKScriptMessageHandler协议,实现方法:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if message.name == "ClickMe" {
        print(message.body)
    }
}

6. 文章中的html代码

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
        <title>Hello</title>
    </head>
    <body>
        <p>Hello World!</p>
        <input style = "display:none" name = "input" value = "I am input" / >
        <button type="button" onclick="alertAction()">alert</button>
        <button type="button" onclick="confirmAction()">confirm</button>
        <button type="button" onclick="promptAction()">prompt</button>
        <script type="text/javascript">
            function alertAction() {
                window.alert("click me alert!");
                window.webkit.messageHandlers.ClickMe.postMessage({"name": "wangyun", "age": 35})
            }
        
            function confirmAction() {
                confirm("你确定要喝水吗?")
            }
        
            function promptAction() {
                prompt("请输入您的名字", "jack.")
            }
        </script>
    </body>
</html>
上一篇下一篇

猜你喜欢

热点阅读