iOS UI入门——Swift下WKWebView的使用

之前有写过Objective-C语法下WKWebView的使用,基本包含了界面和与h5的交互,这里主要写Swift语法下WKWebView的使用。直接上代码吧,说明基本都在注释里。

import UIKit
import WebKit

class ViewController: UIViewController,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler{

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.backgroundColor = UIColor.white
        self.setupWebView()
    }

    func setupWebView() {
        self.view.addSubview(self.webView)
    }

    //MARK:-WKUIDelegate
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        // 在JS端调用alert函数时,会触发此代理方法。
        // JS端调用alert时所传的数据可以通过message拿到
        // 在原生得到结果后,需要回调JS,是通过completionHandler回调
        let alertView = UIAlertController.init(title: "提示", message: message, preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.destructive) { (action:UIAlertAction) in
            //确定
            completionHandler()
        }
        alertView.addAction(okAction)
    }

    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        // JS端调用confirm函数时,会触发此方法
        // 通过message可以拿到JS端所传的数据
        // 在iOS端显示原生alert得到YES/NO后
        // 通过completionHandler回调给JS端
        let alertView = UIAlertController.init(title: "提示", message:message, preferredStyle: UIAlertControllerStyle.alert)
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel) { (action:UIAlertAction) in
            //取消
            completionHandler(false)
        }
        alertView.addAction(cancelAction)
        let okAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.default) { (action:UIAlertAction) in
            //确定
            completionHandler(true)
        }
        alertView.addAction(okAction)
        self.present(alertView, animated: true, completion: nil)
    }

    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        // JS端调用prompt函数时,会触发此方法
        // 要求输入一段文本
        // 在原生输入得到文本内容后,通过completionHandler回调给JS
        let alertTextField = UIAlertController.init(title: "请输入", message: "JS调用输入框", preferredStyle: UIAlertControllerStyle.alert)
        alertTextField.addTextField { (textField:UITextField) in
            //设置textField相关属性
            textField.textColor = UIColor.red
        }
        let okAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.destructive) { (action:UIAlertAction) in
            //确定
            completionHandler(alertTextField.textFields?.last?.text)
        }
        alertTextField.addAction(okAction)
        self.present(alertTextField, animated: true, completion: nil)
    }

    //MARK:-WKNavigationDelegate
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        //页面开始加载,可在这里给用户loading提示
    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        //内容开始到达时
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //页面加载完成时
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        //页面加载出错,可在这里给用户错误提示
    }

    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        //收到服务器重定向请求
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // 在请求开始加载之前调用,决定是否跳转
        decisionHandler(WKNavigationActionPolicy.allow)
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        //在收到响应开始加载后,决定是否跳转
        decisionHandler(WKNavigationResponsePolicy.allow)
    }

    //MARK:-WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //h5给端传值的内容,可在这里实现h5与原生的交互时间
        let messageDic = message.body
        print(messageDic)

    }

    //MARK:-lazy
    lazy var webView: WKWebView = {
        let myWebView = WKWebView.init(frame: self.view.frame)
        let web_url = URL.init(string: "http://www.baidu.com")
        myWebView.load(URLRequest.init(url: web_url!))
        myWebView.navigationDelegate = self
        myWebView.uiDelegate = self
        return myWebView
    }()

    lazy var webConfiguration: WKWebViewConfiguration = {
        let configuration = WKWebViewConfiguration.init()
        let preferences = WKPreferences.init()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        configuration.preferences = preferences
        configuration.userContentController = self.webUserContentController
        return configuration
    }()

    lazy var webUserContentController: WKUserContentController = {
        let userConetentController = WKUserContentController.init()
        userConetentController.add(self, name: "webViewApp")
        return userConetentController
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

你可能感兴趣的:(iOS开发UI入门,Swift入门编程实战)