首先将获取html的图片和图片点击的方法注入到web里面去:
let js = "var srcArr=[]; var allImage=document.getElementsByTagName('img');for(var i=0;i<allImage.length;i++){var image = allImage[i]; image.index = i;srcArr.push({'pic_url': image.src});image.onclick = function () {window.webkit.messageHandlers.\(getHtmlImagesHandlerName).postMessage({'index':this.index,'srcArr':srcArr});}}"
let userScript = WKUserScript.init(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let config = WKWebViewConfiguration.init()
let uservc = WKUserContentController.init()
uservc.addUserScript(userScript)
uservc.add(self, name: getHtmlImagesHandlerName)
config.userContentController = uservc
webView = WKWebView.init(frame: .zero, configuration: config)
上面的代码就是获取当前点击图片的下标和图片地址的数组
//WKScriptMessageHandler 这个是协议
extension ASRealTimeDetailViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == getHtmlImagesHandlerName {
let bodyTemp = message.body as! [String: Any]
let index = bodyTemp["index"] as! Int
let images = bodyTemp["srcArr"] as! Array<Any>
//下面这个代码是我自己封装的查看网络图片的浏览器
showWebViewBrowser(index, images: images)
}
}
}
可能HTML文字和图片没有适应当前屏幕大小,可以加入一下js代码
guard let m = self.indexModel.detailNewsModel else { return }
let html = "<html> \n <head> \n <meta name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,viewport-fit=cover'/> \n <style type=\"text/css\"> img { max-width: 100%; height: auto } \n body {font-size:14px;}\n </style> \n </head> \n <body> \(m.content ?? "") </body></html>"
htmlString = html
webView.loadHTMLString(html, baseURL: nil)