Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to save WKWebview content for offline reading?

Tags:

ios

swift

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.

like image 513
lypw2009 Avatar asked May 14 '18 02:05

lypw2009


People also ask

How do I add WKWebView to my storyboard?

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.

How do I refresh 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.


Video Answer


1 Answers

 //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)
            }
        }
}
like image 117
Vivek Kumar Avatar answered Nov 07 '22 08:11

Vivek Kumar