美文网首页
9.3、WKWebView

9.3、WKWebView

作者: 艾希_可可 | 来源:发表于2018-06-27 12:04 被阅读77次

    import UIKit
    import WebKit
    import JavaScriptCore
    let DeviceWidth = UIScreen.main.bounds.width
    let DeviceHeight = UIScreen.main.bounds.height

    class WkWebViewController: UIViewController,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler {
    var webUrl:String?
    var titleName:String? = ""

        override func viewDidLoad() {
        super.viewDidLoad()
            self.setNav()
    

    // 1、进入网页
    // self.webUrl = "http://www.baidu.com"
    // 查看弹出框
    // self.webUrl = "http://evt.tiancity.com/csol2/1565/home/index.php"
    // 事件交互
    self.webUrl = "https://testm.modai.cc/Activity/AnniversaryAward.aspx#url=app"
    // self.webUrl = "https://www.apple.com"
    // self.webUrl = "http://192.168.0.160:8089/Activity/riskEntrance"
    self.view.addSubview(self.wkwebView)
    self.wkwebView.addSubview(self.progressView)
    self.wkwebView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
    }
    func setNav() {
    self.title = titleName
    // 适应导航
    self.automaticallyAdjustsScrollViewInsets = true
    let leftBtns = UIBarButtonItem(image: UIImage.init(named: "back")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), style: .plain, target: self, action: #selector(backToOneVC))
    self.navigationItem.leftBarButtonItem = leftBtns
    }
    @objc func backToOneVC() {
    if self.wkwebView.canGoBack {
    self.wkwebView.goBack()
    }else{
    self.navigationController?.popViewController(animated: true)
    }
    }
    lazy var configuration: WKWebViewConfiguration = {
    let config = WKWebViewConfiguration()
    // 设置偏好设置
    config.preferences = WKPreferences()
    // 默认为0
    config.preferences.minimumFontSize = 10
    // 默认认为YES
    config.preferences.javaScriptEnabled = true
    // 在iOS上默认为NO,表示不能自动通过窗口打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = false
    // web内容处理池
    config.processPool = WKProcessPool()
    // 通过JS与webview内容交互
    config.userContentController = WKUserContentController()
    // 注入JS对象名称AppModel,当JS通过AppModel来调用时,
    // // 我们可以在WKScriptMessageHandler代理中接收到
    // config.userContentController.add(self, name: "AwardBuy")
    return config
    }()
    lazy var wkwebView: WKWebView = {
    //获取导航栏高度
    let navHeight = self.navigationController?.navigationBar.frame.height
    //获取状态栏高度
    let statusHeight = UIApplication.shared.statusBarFrame.height
    let wkwebview = WKWebView(frame: CGRect(x: 0, y: navHeight!+statusHeight, width: DeviceWidth, height: DeviceHeight-(navHeight!+statusHeight)), configuration: self.configuration)
    wkwebview.uiDelegate = self
    wkwebview.navigationDelegate = self
    wkwebview.allowsBackForwardNavigationGestures = true
    wkwebview.load(NSURLRequest(url: URL(string: self.webUrl!)!) as URLRequest)
    return wkwebview
    }()
    lazy var progressView : UIProgressView = {
    let pp = UIProgressView.init(frame: CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: 2))
    pp.progress = 0.0
    pp.tintColor = UIColor.red
    // pp.backgroundColor = UIColor.lightGray
    // pp.transform = CGAffineTransform.init(scaleX: 1, y: 1)
    return pp
    }()
    // 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)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "estimatedProgress" {
    self.progressView.alpha = 1.0
    progressView.setProgress(Float(self.wkwebView.estimatedProgress), animated: true)
    //进度条的值最大为1.0
    if(self.wkwebView.estimatedProgress >= 1.0) {
    UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: {
    self.progressView.alpha = 0.0
    }) { (finish:Bool) in
    self.progressView.progress = 0
    }
    }
    }
    }
    func webView(
    webView: WKWebView, didFinish navigation: WKNavigation!) {
    self.wkwebView.evaluateJavaScript("AwardBuy", completionHandler: {(any,error) in
    print("111111---------AwardBuy-------------")
    if error != nil{
    print("---------AwardBuy-------------")
    }
    })

    }
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("点击h5 返回=====\(message)")
        if message.name == "AwardBuy" {
            let dict = message.body as! NSDictionary
            
            let values = dict["tag"]
            print(values ?? "000")
            if let a = values {
                let b:Int = a as! Int
                print("进入判断===\(a)")
                if b == 4 {//收藏
                    self.collectAction(dict: dict)
                }else if b == 3 {//分享
                    
                }else if b == 1 {//支付
             
                }
            }
        }else{
            print("点击h5 其他函数=====\(message)")
        }
    }
    func collectAction(dict:NSDictionary) {
        let alert = UIAlertController(title: "温馨提示", message: "收藏成功", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "知道了", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    

    }

    相关文章

      网友评论

          本文标题:9.3、WKWebView

          本文链接:https://www.haomeiwen.com/subject/mrsbyftx.html