iOS开发swift -- WKWebView JS 交互

基础设置

 //导入 UIKit、WebKit 并遵循 WKUIDelegate、WKNavigationDelegate、WKScriptMessageHandler代理
    override func viewDidLoad() {
        super.viewDidLoad()

        let rightBarItem = UIBarButtonItem(title: "心愿种子", style: .plain, target: self, action: #selector(wishSeed))
        navigationItem.rightBarButtonItem = rightBarItem
        
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        //基本配置
        let config = WKWebViewConfiguration()
        //创建UserContentController(提供JavaScript向webView发送消息的方法)
        let userContent = WKUserContentController()
        //添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除
        userContent.add(self, name: "NativeMethod")
        //将UserConttentController设置到配置文件
        config.userContentController = userContent
        webView = WKWebView.init(frame: CGRect.zero, configuration: config)
        
        let path = Bundle.main.path(forResource: "多多攒钱", ofType: ".html")
        let url = NSURL.init(fileURLWithPath: path!)
        webView.load(NSURLRequest.init(url: url as URL) as URLRequest)
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        //进度条
        progBar = UIProgressView()
        progBar.progress = 0.0
        progBar.alpha = 1.0
        progBar.tintColor = UIColor.red
        webView.addSubview(progBar)

        progBar.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(webView)
            make.height.equalTo(3)
        }

        //清理缓存
        if UIDevice.current.systemVersion.compare("9.0") ==  ComparisonResult.orderedAscending{
            let types = NSSet.init(array: [WKWebsiteDataTypeDiskCache,WKWebsiteDataTypeMemoryCache])
            WKWebsiteDataStore.default().removeData(ofTypes: types as! Set, modifiedSince: Date()) {
            }
        }else
        {
            let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first
            let cookiePath = libraryPath?.appending("/Cookies")
            do {
                try FileManager.default.removeItem(atPath: cookiePath!)
            } catch {
                // 删除失败
            }
        }
   }

进度条

    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "estimatedProgress" {
            progBar.setProgress(Float(webView.estimatedProgress), animated: true)
            if(self.webView.estimatedProgress >= 1.0) {
                UIView.animate(withDuration: 0.2, delay: 0.1, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 0
                })
            }
        }
        
    }

代理方法

    //移除代理和观察者
    func deinit {
        tabBarController?.tabBar.isHidden = false
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "NativeMethod")
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = self.webView.title
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }

    //js中弹出的提示框需要做处理否则没有
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in
            completionHandler()
        }))
        self.present(alert, animated: true, completion: nil)
    }

交互方法

    //js调用swift
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //"NativeMethod"需要与userContent.add(self, name: "NativeMethod")中相同
        if message.name == "NativeMethod" {
            if message.body as! String == "first" {
                //可根据body的值调用相应的方法
                debugPrint(message.body)
            }
        }
    }
    
    //swift调用js
    func wishSeed() {
        self.webView.evaluateJavaScript("clear_cache('哈哈哈哈哈')", completionHandler: nil)
    }

html

    function clear_token() {
        window.webkit.messageHandlers.NativeMethod.postMessage('first');
    }

如有不妥,请多多指教 :)

你可能感兴趣的:(iOS开发swift -- WKWebView JS 交互)