美文网首页
iOS WKWebview 图片浏览

iOS WKWebview 图片浏览

作者: 9岁就很6 | 来源:发表于2022-04-11 11:46 被阅读0次

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
      //计算webView高度
        updateWebViewHeight()
        
        // 禁用用户选择
        webView.evaluateJavaScript("document.documentElement.style.webkitUserSelect='none';") { result, error in
            
        }
        
        // 禁用长按弹出框
        webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';") { result, error in
            
        }
        
        let javascript = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
        webView.evaluateJavaScript(javascript, completionHandler: nil)
        
        
        let jsGetImages =
        "function getImages(){" +
        "var objs = document.getElementsByTagName(\"img\");" +
        "var imgScr = '';" +
        "for(var i=0;i<objs.length;i++){" +
        "imgScr = imgScr + objs[i].src + '+';" +
        "};" +
        "return imgScr;" +
        "};"
        webView.evaluateJavaScript(jsGetImages, completionHandler:nil)
        //添加图片可点击js
        let jsClickImage =
            "function registerImageClickAction(){" +
            "var imgs=document.getElementsByTagName('img');" +
            "var length=imgs.length;" +
            "for(var i=0;i<length;i++){" +
            "img=imgs[i];" +
            "img.onclick=function(){" +
            "window.location.href='image-preview:'+this.src}" +
            "}" +
            "}"
        webView.evaluateJavaScript(jsClickImage, completionHandler: nil)
        webView.evaluateJavaScript("getImages()") { result, error in
            //获取h5页面的图片url合集
            guard let urlResult = result as? String else {
                return
            }
            //所有Url的数组
            var urlArry = urlResult.components(separatedBy: "+")
            urlArry.removeLast()
            self.imgUrlArray.append(contentsOf: urlArry)
            for url in self.imgUrlArray{
                let photo = SKPhoto.photoWithImageURL(url)
                photo.shouldCachePhotoURLImage = false // you can use image cache by true(NSCache)
                self.images.append(photo)
            }
        }
        webView.evaluateJavaScript("registerImageClickAction();", completionHandler:nil)
        
        self.webView.isHidden = false
    }

 
    @available(iOS 8.0, *)
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let requestString = navigationAction.request.url?.absoluteString
          print(requestString!)
          if (requestString?.hasPrefix("image-preview"))!{
            let imgUrl = NSString.init(string: requestString!).substring(from: "image-preview:".count )
            guard let index = imgUrlArray.firstIndex(of: imgUrl) else {
                let browser = SKPhotoBrowser(photos: images)
                CommonUtil.getCurrentVC()?.present(browser, animated: true, completion: nil)
                return
            }
            let browser = SKPhotoBrowser(photos: images)
            browser.initializePageIndex(index)
            CommonUtil.getCurrentVC()?.present(browser, animated: true, completion: nil)
          }
          decisionHandler(.allow) //一定要加上这句话
    }


    func updateWebViewHeight() {
        webView.evaluateJavaScript("document.body.scrollHeight") { result, error in
            //获取页面高度,并重置webview的frame
            if let value = result {
                guard let lastHeight  = value as? Double else { return }
                if (lastHeight == self.webViewHeight) {
                    return
                }
                DispatchQueue.main.async {
                    self.webViewHeight = lastHeight
                }
            }
        }
    }

相关文章

网友评论

      本文标题:iOS WKWebview 图片浏览

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