美文网首页1
iOS 如何监听WKWebView的内容滑动到底部

iOS 如何监听WKWebView的内容滑动到底部

作者: 效宇笑语 | 来源:发表于2019-11-06 16:49 被阅读0次

     最近的项目有一个需求,就是需要监听WKWebView的内容是否已经滑动到底部,使用WKWebView展示用户条款的静态web页面,如果用户滑动内容到WKWebView窗口的底部的话,同意按钮就可以点击。

     一开始以为这个需求很简单,但是实践的时候才知道坑挺多的,先简单来说说WKWebView渲染过程,WKWebView内部有一个UIScrollView,实际的绘制最终呈现在这个ScrollView上,在WKWebView获取到HTML文件以及开始进行DOM渲染时,不会提前计算出该DOM的实际高度,而是将ContentSize的高度设置成WKWebView的height值,然后进行计算、渲染,在将元素呈现在ScrollView上时,会修改ScrollView的ContentSize属性,在WKWebView调用func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)时,ScrollView的ContentSize属性依旧是之前计算的值:

    1238.0
    490.0
    3904.3333333333335
    9862.0                     // didFinish时取到的值
    9834.0                     // didFinish之后取到的值
    9834.0
    9834.0
    9834.0
    9834.0
    9834.0
    

     渲染DOM事件本身是一件十分复杂的事情,但是如果只是监控Web页面滑动到底部的话应该还是很简单的:

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if (scrollView.isDecelerating || scrollView.isDragging) && !(self.wkWeb?.isLoading ?? true) {
            checkEnableConfirm()
        }
    }
    
    private func checkEnableConfirm() {
        guard let scroll = self.wkWeb?.scrollView else { return }
        if scroll.bounds.height + scroll.contentOffset.y >= scroll.contentSize.height {
            self.btnConfirm.isEnabled = true
        }
    }
    

    但是如果考虑如果返回的HTML内容的高度不够WKWebView的高度怎么办?那就需要在DOM渲染完成后,拿到ScrollView的ContentSize.height属性与WKWebView的高度比较,但是刚刚有说过,这个ContentSize.height属性,在webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)中拿到的是个不准确的值,只能在该回调之后获取,但是WKWebView只有这一个回调告诉你DOM解析完成了,后续在没有能够使用的回调函数了。

      于是我做了一些尝试:

    1. didFinish中做一个延时:
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(500)) {
            checkEnableConfirm()
        }
    }
    

     但是很奇怪的是,依旧获取不到正确的ContentSize的值。

    1. 使用JS可以解决,参考链接:iOS WKWebView detect when reaches bottom,但是该方法有JS交互,但是也算是保底方案,为了尽量避免在应用内使用JS代码和本着Native的问题最好是Native解决,又继续寻找其它的方法。

    2. 既然不知道什么时候WKWebView会修改ScrollView的contentSize,那么就做一个KVO看看WKWebView修改contentSize的时机,结果发现每当WKWebView的回调函数func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)执行完,都会去修改一次contentSize属性,而且这次修改的值时正确的值(但是如果页面是动态的页面,并且后续会有JS获取新的资源的情况下,那么此时获取到的值依旧不准确,这种情况下,只能通过JS与Native协作才可以,由于用户协议页面是一个静态html所以可行),最终采用了这种方法代码如下:

    class ReagreementDetailController: UIViewController, WKUIDelegate, WKNavigationDelegate, UIScrollViewDelegate {
    
        @IBOutlet weak var btnConfirm: UIButton!
        private var wkWeb: WKWebView?
        private var isFinished: Bool = false
        private var currentReagreement: (isSelected: Bool, title: String, url: String)?
        private var confirmDelegate: (() -> Void)?
        var url: URL?
        override func viewDidLoad() {
            super.viewDidLoad()
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
            self.lbReagreementTitle.font = UIFont.globalFont(ofSize: UIFont.kFontSize15D7)
            self.lbReagreementTitle.textColor = kGlobalColorGreen
            self.wkWeb = WKWebView.init(frame: self.view.bounds, configuration: WKWebViewConfiguration.init())
            self.wkWeb?.uiDelegate = self
            self.wkWeb?.navigationDelegate = self
            self.wkWeb?.scrollView.delegate = self
            self.view.addSubView(wk: self.wkWeb!)
            self.wkWeb?.scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
            self.btnConfirm.isEnabled = false
            self.wkWeb?.allowsBackForwardNavigationGestures = true
            self.startLoad()
            // Do any additional setup after loading the view.
        }
        
        deinit {
            self.wkWeb?.scrollView.removeObserver(self, forKeyPath: "contentSize")
        }
        
        func setReagreement(_ item: (isSelected: Bool, title: String, url: String), delegate: @escaping (() -> Void)) {
            self.currentReagreement = item
            self.confirmDelegate = delegate
        }
        
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            guard let path = keyPath, let value = change?[NSKeyValueChangeKey.newKey] as? CGSize, path == "contentSize" else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context); return }
            if isFinished {
                if value.height <= self.wkWeb?.bounds.height {
                    self.btnConfirm.isEnabled = true
                }
                isFinished = false
            }
        }
        
        @IBAction func btnConfirmClicked(_ sender: Any) {
            self.confirmDelegate?()
            TransitionManager.sharedInstance.transitionBack()
        }
    
        private func startLoad() {
            guard let reURL = url else { return }
            self.wkWeb?.load(URLRequest.init(url: reURL))
        }
        
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            if (scrollView.isDecelerating || scrollView.isDragging) && !(self.wkWeb?.isLoading ?? true) {
                checkEnableConfirm()
            }
        }
        
        @available(iOS 13.0, *)
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
            decisionHandler(.allow, preferences)
        }
        
        func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
            decisionHandler(.allow)
        }
        
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            decisionHandler(.allow)
        }
        
        func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
            /*
            guard let url = navigationAction.request.url else { return nil }
            guard let webViewController = TransitionManager.sharedInstance.viewControllerById(.kSubWebVC) as? WebViewController else { return nil }
            webViewController.presentationStyle = .present
            webViewController.isBtnRefreshVisable = false
            self.present(webViewController, animated: true, completion: {
                webViewController.loadUrl(url: url.absoluteString)
            })
            */
            return nil
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            isFinished = true
        }
        
        private func checkEnableConfirm() {
            guard let scroll = self.wkWeb?.scrollView else { return }
            if scroll.bounds.height + scroll.contentOffset.y >= scroll.contentSize.height {
                self.btnConfirm.isEnabled = true
            }
        }
    }
    
    

    相关文章

      网友评论

        本文标题:iOS 如何监听WKWebView的内容滑动到底部

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