本文主要是介绍APP(iOS)端 从网页拿到第一张图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
class GetWebviewImageHelper: NSObject, WKScriptMessageHandler {
var didGetImg: ((UIImage?) -> (Void))?
init(view: WKWebView) {
super.init()
self.initWebket(view)
}
//初始化 webview 并添加 对 "getimage"(此处是死的) 监听
private func initWebket(webView: WKWebView) {
webView.configuration.userContentController.addScriptMessageHandler(self, name: "getimage")
}
///获取网页图片 //(js 代码)
func getWebViewImages(view: WKWebView) {
let url = "javascript:(function(){var imgs = document.getElementsByTagName(\"img\");if (imgs.length > 0) {" +
"window.webkit.messageHandlers.getimage.postMessage(imgs[0].src);" +
"}" + "})()"
view.evaluateJavaScript(url) { (obj, err) in
if let error = err {
debugPrint(error.domain)
}
}
}
///受到回调
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let urlStr = message.body as? String {
let manager = SDWebImageDownloader()
manager.downloadImageWithURL(NSURL(string: urlStr), options: SDWebImageDownloaderOptions(), progress: nil, completed: { (img, data, error, bol) in
self.didGetImg?(img)
})
}
}
//移除监听
func releaseMessageHandler(webView: WKWebView?) {
if let wb = webView {
wb.configuration.userContentController.removeScriptMessageHandlerForName("getimage")
}
}
}
上面的类是获取 image类 需要在 wekwebview 实例化
然后在webview 的 代理方法里面调用 getWebViewImages 方法
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
if let title = webView.title {
webTitle = title
netLoadFinsh?(title)
if let h = helper {
h.getWebViewImages(webView)
}
}
}
同时在deinit 时 移除对webview的监听
deinit {
if let h = helper {
h.releaseMessageHandler(webView)
}
}
这篇关于APP(iOS)端 从网页拿到第一张图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!