是否可以保存WKWebview内容以供离线阅读?

时间:2018-05-14 02:10:09

标签: ios swift

我需要保存WKWebView上加载的内容以供离线阅读,包括图像。然后,即使没有网络访问,用户也可以再次查看网页。

WKWebView是否支持缓存?我该如何实施呢?

用于离线观看的" UIWebView网页缓存中的答案"用于UIWebview不适用于WKWebView,因此它们是不同的。 我也知道我们可以为WKWebViewCache启用应用程序缓存,但它将使用将被拒绝的私有API。

2 个答案:

答案 0 :(得分:1)

 //Two ways i know so far
//1st : after loading the page when user is online,get the html from WKWebView as follows :




webView.evaluateJavaScript("document.documentElement.outerHTML.toString()", 
                           completionHandler: { (html: Any?, error: Error?) in
    print(html)
})




//Second way is that inject script to get html from WKWebView as follows>

 let script = WKUserScript(source: javascriptString, injectionTime: injectionTime, forMainFrameOnly: true)
userContentController.addUserScript(script)
self.webView.configuration.userContentController.addScriptMessageHandler(self, name: "didGetHTML")
func userContentController(userContentController: WKUserContentController,
        didReceiveScriptMessage message: WKScriptMessage) { if message.name == "didGetHTML" {
            if let html = message.body as? String {
                print(html)
            }
        }
}

答案 1 :(得分:0)

//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")
                                    }
        })
    }
}