使用WebViewJavascriptBridge实现Swift

2020-06-30  本文已影响0人  玉思盈蝶

代码如下:

import UIKit
import WebViewJavascriptBridge
import DesEncrypt
import SwiftyJSON

class NavigationBarWebView: UIView {
    
    var goback: CallBack?
    var saveCallback: CallBack?
    
    private lazy var leftButton: UIButton = {
        let btn = UIButton()
        btn.setTitle(" " + GLOBAL_LANGUAGE("返回"), for: .normal)
        btn.setImage(UIImage(named: "back_leftArrow"), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        btn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        return btn
    }()
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "ebebeb")
        label.font = UIFont.systemFont(ofSize: 21)
        return label
    }()
    private lazy var saveButton: UIButton = {
        let btn = UIButton()
        btn.setTitle(" " + GLOBAL_LANGUAGE("保存"), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        btn.addTarget(self, action: #selector(saveBtnClick), for: .touchUpInside)
        return btn
    }()

    init(with frame: CGRect, title: String, hasRightBtn: Bool = false) {
        super.init(frame: .zero)
        
        setupUI(hasRightBtn: hasRightBtn)
        layoutView(hasRightBtn: hasRightBtn)
        titleLabel.text = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension NavigationBarWebView {
    
    private func setupUI(hasRightBtn: Bool) {
        self.backgroundColor = UIColor(hexString: "1f2124")
        addSubview(leftButton)
        addSubview(titleLabel)
        if hasRightBtn {
            addSubview(saveButton)
        }
    }
    
    private func layoutView(hasRightBtn: Bool) {
        leftButton.snp.makeConstraints { (make) in
            make.top.left.bottom.equalTo(self)
            make.width.equalTo(120)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        if hasRightBtn {
            saveButton.snp.makeConstraints { (make) in
                make.top.bottom.equalTo(self)
                make.right.equalTo(self).inset(20)
                make.width.equalTo(120)
            }
        }
    }
    
    @objc private func leftBtnClick() {
        self.goback?()
    }
    
    @objc private func saveBtnClick() {
        self.saveCallback?()
    }
}


class NewPointMallViewController: UIViewController {

    var urlhost: String = HHTSwitchGlobalData.shared.pointUrlStr + "?"
// UIWebView实现
//    private lazy var webView: UIWebView = {
//        let web = UIWebView(frame: .zero)
//        web.delegate = self
//        web.scrollView.bounces = false
//        return web
//    }()
    
    // WKWebView实现
    private lazy var webView: WKWebView = {
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences
        configuration.userContentController = WKUserContentController()
        
        let web = WKWebView(frame: .zero, configuration: configuration)
        web.uiDelegate = self
        web.scrollView.bounces = false
        return web
    }()
    
    var bridge: WebViewJavascriptBridge?
    
    private lazy var navigationView: NavigationBarWebView = NavigationBarWebView(with: .zero, title: GLOBAL_LANGUAGE("捞币换礼"))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        registerHandler()
        configWebView()
        navigationView.goback = {[weak self] in
            guard let `self` = self else {
                return
            }
            self.chargeGoBack()
        }
    }
    func registerHandler() {
        
        func parameterValid(with data: Any?) -> (result: Bool, data: [String: Any]) {
            if let parameter = data, parameter is NSDictionary {
                let dic = parameter as! NSDictionary
                if let params = dic as? [String: Any] {
                    return (true, params)
                }
            }
            
            return (false, [:])
        }
        
        func callback(with closure: WVJBResponseCallback?, data: [String: Any]) {
            if let call = closure {
                call(data as NSDictionary)
            }
        }
        
        self.bridge = WebViewJavascriptBridge(forWebView: webView)
        self.bridge?.registerHandler("fetchSellOut", handler: { (data, responseCallback) in
            let params = parameterValid(with: data)
            var result: [[String: String]] = []
            //判断参数是否有效
            if params.result, let unicode = params.data["ids"], let unicodeStr = unicode as? String {
            // 拿到数据操作
            }
            // 给H5传值
            callback(with: responseCallback, data: ["result":result])
        })
        
        
        self.bridge?.registerHandler("dishOrder", handler: { (data, responseCallback) in
            let params = parameterValid(with: data)
            if params.result, let ids = params.data["data"], let list = ids as? [[String: String]] {
            // 拿到数据操作
            
            }
        })
        
    }
}

extension NewPointMallViewController {
    private func setupUI() {
        view.addSubview(navigationView)
        view.addSubview(webView)
        navigationView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(NavigationBarH)
        }
        webView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.top.equalTo(navigationView.snp.bottom)
        }
        
    }
    
    private func configWebView() {
        URLCache.shared.removeAllCachedResponses()
        let key = CustomerManager.shared.customerKey ?? ""
        let storeId = WaiterManager.shared.currentShop["shopNo"] as? String ?? ""
        let customerKey = HDLDesEncrypt.encryptUse3DES(key, key: "haidilao2015818secretKey")!
        let mobile = CustomerManager.shared.mobileno ?? ""
        let totalIntegral = CustomerManager.shared.totalScore
        let tableId = TableManager.shared.currentTableNo
        let waiterNo = WaiterManager.shared.waiterNo
        let waiterName = WaiterManager.shared.waiterName
        let timeStamp = NSDate().timeIntervalSince1970
        let tableUid = TableManager.shared.currentTableID
        let orderNo = TableManager.shared.currentTableBillID
        let waiterId = WaiterManager.shared.waiterID
        let userId = key
        guard let urlPath = "storeId=\(storeId)&customerKey=\(customerKey)&mobile=\(mobile)&totalIntegral=\(totalIntegral)&tableId=\(tableId)&waiterNo=\(waiterNo)&waiterName=\(waiterName)&timeStamp=\(timeStamp)&tableUid=\(tableUid)&type=1&orderNo=\(orderNo)&waiterId=\(waiterId)&userId=\(userId)".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed) else {
            return
        }
        guard let url = URL(string: urlhost + urlPath) else {
            return
        }
        
        let request = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10)
        
        webView.load(request)
    }

    private func chargeGoBack() {
    // UIWebView的注入代码
//        if let webSucsessGoback = self.webView.stringByEvaluatingJavaScript(from: "webGoBack()") {
//            // 网页内部跳转成功
//            if webSucsessGoback != "0" {
//                return
//            }
//        }
    
// WKWebView的注入代码  
 webView.evaluateJavaScript("webGoBack()") { (result, err) in
            print(result ?? "", err ?? "")
            if result == nil {
                return
            }
            self.dismiss(animated: false) {
                self.getCouponListData()
            }
        }
    }
}

// UIWebView代理
extension NewPointMallViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        HUDManager.showAutoDismissFailedMessage(GLOBAL_LANGUAGE("加载出现错误") + "\(error),正在关闭页面")
        self.dismiss(animated: true, completion: nil)
    }
    
}

// WKWebView代理
extension NewPointMallViewController: WKUIDelegate {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            print(message.name)
            print(message.body)
    }
}

注意点:

1、之前也写过这样一篇博客,大概也就是学习了下WebViewJavascriptBridge的使用,今天这是总结了下UIWebView转WKWebView的使用;
2、注意UIWebView的stringByEvaluatingJavaScript转WKWebView的区别;

参考链接:

https://www.jianshu.com/p/ec1d94e4738c

上一篇下一篇

猜你喜欢

热点阅读