I need to save the content loaded on the WKWebView for offline reading including images. Then the users can view the web page again even there is no network access.
Does WKWebView support caching it? How can I implement it?
The answer in "UIWebView webpage caching for offline viewing" is for UIWebview not for WKWebView, so they are different. And I also know we can enable app cache for WKWebViewCache but it will use private API which will be rejected.
First add the web view as a UIWebView outlet in the storyboard / IB. This will give you a property like this: @property (weak, nonatomic) IBOutlet UIWebView *webView; Then just edit your code to change it to a WKWebView.
The WKWebView already contains a scrollview. All you need to do is create the refresh control, assign a target function that will get called when a user initiates a refresh, and attach the refresh control to the scrollview.
//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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With