iOS開發(fā)swift -- WKWebView JS 交互

基礎(chǔ)設(shè)置

 //導(dǎo)入 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()
        //創(chuàng)建UserContentController(提供JavaScript向webView發(fā)送消息的方法)
        let userContent = WKUserContentController()
        //添加消息處理,注意:self指代的對象需要遵守WKScriptMessageHandler協(xié)議,結(jié)束時需要移除
        userContent.add(self, name: "NativeMethod")
        //將UserConttentController設(shè)置到配置文件
        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)
        }
        
        //進(jìn)度條
        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<String>, modifiedSince: Date()) {
            }
        }else
        {
            let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first
            let cookiePath = libraryPath?.appending("/Cookies")
            do {
                try FileManager.default.removeItem(atPath: cookiePath!)
            } catch {
                // 刪除失敗
            }
        }
   }

進(jìn)度條

    
    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調(diào)用swift
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //"NativeMethod"需要與userContent.add(self, name: "NativeMethod")中相同
        if message.name == "NativeMethod" {
            if message.body as! String == "first" {
                //可根據(jù)body的值調(diào)用相應(yīng)的方法
                debugPrint(message.body)
            }
        }
    }
    
    //swift調(diào)用js
    func wishSeed() {
        self.webView.evaluateJavaScript("clear_cache('哈哈哈哈哈')", completionHandler: nil)
    }

html

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容