Swift: WKWebView的简单使用

import UIKit
import WebKit
class MyViewController: UIViewController {

    var webView = WKWebView()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.progressView.frame = CGRect(x:0,y:64,width:self.view.frame.size.width,height:2)
        self.progressView.isHidden = false
        UIView.animate(withDuration: 1.0) {
            self.progressView.progress = 0.0
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
      
        let url = "https://www.jianshu.com/u/5ab7d4b14cbe"
        
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
        view.addSubview(webView)
        webView.navigationDelegate = self
        let mapwayURL = URL(string: url)!
        let mapwayRequest = URLRequest(url: mapwayURL)
        webView.load(mapwayRequest)
       
        view.addSubview(self.progressView)
    }
    
    
    // 进度条
    lazy var progressView:UIProgressView = {
        let progress = UIProgressView()
        progress.progressTintColor = UIColor.orange
        progress.trackTintColor = .clear
        return progress
    }()

}

extension MyViewController:WKNavigationDelegate{
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
        self.navigationItem.title = "加载中..."
        /// 获取网页的progress
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = Float(self.webView.estimatedProgress)
        }
    }
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        
    }
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
        self.title = self.webView.title
        
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = 1.0
            self.progressView.isHidden = true
        }
    }
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        
        UIView.animate(withDuration: 0.5) {
            self.progressView.progress = 0.0
            self.progressView.isHidden = true
        }
        /// 弹出提示框点击确定返回
        let alertView = UIAlertController.init(title: "提示", message: "加载失败", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title:"确定", style: .default) { okAction in
            _=self.navigationController?.popViewController(animated: true)
        }
        alertView.addAction(okAction)
        self.present(alertView, animated: true, completion: nil)
        
    }
    
}

JS调Native APP :首先,得改下创建WKWebView的代码,添加进自己的一些配置,代码如下:

lazy var webView : WKWebView = {
        /// 自定义配置
        let conf = WKWebViewConfiguration()
        conf.userContentController = WKUserContentController()
        conf.preferences.javaScriptEnabled = true
        conf.selectionGranularity = WKSelectionGranularity.character
        conf.userContentController.add(self, name: "和web那边一样的方法名")
        let web = WKWebView( frame: CGRect(x:0, y:64,width:ScreenW, height:ScreenH),configuration:conf)
        /// 设置访问的URL
        let url = NSURL(string: "http://www.jianshu.com/u/37fe1e005f6c")
        /// 根据URL创建请求
        let requst = NSURLRequest(url: url! as URL)
        /// 设置代理
//        web.uiDelegate = self
        web.navigationDelegate = self
        /// WKWebView加载请求
        web.load(requst as URLRequest)
        
        return web
    }()

接着,要实现WKScriptMessageHandler的方法

extension YourViewControllerName:WKScriptMessageHandler{//用于与JS交互
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if(message.name == "和web那边一样的方法名") {
            print("JavaScript is sending a message \(message.body)")
        }
       
    }
    
}

最后,别忘了在移除MessageHandler哦!否则可能会导致内存泄漏哦。

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //当前ViewController销毁前将其移除,否则会造成内存泄漏
         webView.configuration.userContentController.removeScriptMessageHandler(forName: "和web那边一样的方法名")
    }

你可能感兴趣的:(Swift: WKWebView的简单使用)