//To get image from html you need to implement like this
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")
}
})
}
}