JS交互 点击WKWebView中的图片实现预览效果

JS交互 点击WKWebView中的图片实现预览效果
  • Swift 4.0
  • WKWebView

1.注入js代码 (重点)

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    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)
    webView.evaluateJavaScript("getImages()") { (data, err) in
        let imageUrl:String = data as! String
        var urlArry = imageUrl.components(separatedBy: "+")
        urlArry.removeLast()
        self.imgUrlArray.addObjects(from: urlArry)
        for url in self.imgUrlArray{
            let photo = SKPhoto.photoWithImageURL(url as! String)
            photo.shouldCachePhotoURLImage = false // you can use image cache by true(NSCache)
            self.images.append(photo)
        }
    }
    var jsClickImage:String
    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("registerImageClickAction()", completionHandler: nil)
}

2.使用SKPhotoBrowser框架实现图片预览功能

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 )
        let index = imgUrlArray.index(of: imgUrl)
        let browser = SKPhotoBrowser(photos: images)
        browser.initializePageIndex(index)
        present(browser, animated: true, completion: {})
    }
    decisionHandler(.allow)  //一定要加上这句话 
}

注:可根据需求更改代码

  • 发表于 2018-01-04 14:24
  • 阅读 ( 478 )
  • 分类:ios

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
不写代码的码农
Alan

iOS开发

14 篇文章

作家榜 »

  1. 威猛的小站长 107 文章
  2. Jonny 65 文章
  3. 江南烟雨 33 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 20 文章
  8. Alan 14 文章