从HTML WKWebView下载图像

时间:2018-01-31 14:06:18

标签: ios swift wkwebview

以下是我从WKWebView中加载的网址获取的标记之一

  

< img id =" image_id"命名=" imageName" SRC =" captcha.jpg">

在DidFinish上是否可以将该图像作为UIImage?

1 个答案:

答案 0 :(得分:5)

为实现这一目标,我已经使用了一些库来帮助。

在使用pod(或者carthage或任何你喜欢的东西)的项目中插入以下库:

SwiftSoup

AlamofireImage

一旦你的项目设置了这些库,我们就去了。

在你的故事板中,放置2个元素,我的一个WKWebView和一个ImageView。 只需设置约束以确保测试时所有内容都在屏幕上。

enter image description here

然后在代码中我们将:

import UIKit
import WebKit
import SwiftSoup
import AlamofireImage


class ViewController: UIViewController, WKNavigationDelegate {
    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var imageView: UIImageView!

    let url = URL(string: "https://www.google.com")
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        webView.navigationDelegate = self

        let urlReq = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 1)
        webView!.load(urlReq)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
                                   completionHandler: { (html: Any?, error: Error?) in
                                    do{
                                        let doc: Document = try SwiftSoup.parse(html as! String)
                                        let pngs: Elements = try doc.select("img[src$=.png]")
                                        let srcsStringArray: [String?] = pngs.array().map { try? $0.attr("src").description }
                                        for imgs in srcsStringArray {
                                            if let imgUrl = imgs {
                                                var finalUrl = URL(string: "")
                                                if imgUrl.contains("http") {
                                                    finalUrl = URL(string: String(format: imgUrl))
                                                } else {
                                                    finalUrl = URL(string: String(format: "%@%@", (self.url?.absoluteString)!, imgUrl))
                                                }
                                                self.imageView.af_setImage(withURL: finalUrl!)
                                                print(finalUrl) //debug URL
                                            }
                                        }
                                    } catch Exception.Error(let type, let message){
                                        print(type, message)
                                    } catch {
                                        print("error")
                                    }
        })
    }
}

此示例按原样运行。

当然,您需要根据自己的需要进行调整,但是您必须具备所有要素。

编辑1:

我只有一张图片,如果您有多张图片,则必须在线上正确处理:

for imgs in srcsStringArray {...}

编辑2:

准备好Captcha,获取精确加载的图像。 在这种情况下,您不需要 Alamofire 也不需要 SwiftSoup

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var imageView: UIImageView!

    let url = URL(string: "YOUR_URL")

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        webView.navigationDelegate = self

        let urlReq = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 1)
        webView!.load(urlReq)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        let str = "var c = document.createElement('canvas'); var ctx = c.getContext('2d'); ctx.drawImage(document.getElementById('captcha_id'), 100, 40); var value = c.toDataURL(); value.split(',')[1]; "

        self.webView.evaluateJavaScript(str) { (value, error) in
             if error == nil {
                 if let img = value as? String {
                      self.imageView.image = self.base64ToImage(base64: img)
                 }
             }
         }
    }

    func base64ToImage(base64: String) -> UIImage? {
        var img: UIImage = UIImage()
        if (!base64.isEmpty) {
            if let decodedData = NSData(base64Encoded: base64 , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
                if let decodedimage = UIImage(data: decodedData as Data) {
                    img = (decodedimage as UIImage?)!
                    return img
                }
            }
        }
        return nil
    }
}