Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache for WKWebView

I am having trouble with my custom internet browser. I am using WKWebView. I have tabs in my app. If I click on a tab new NSURLRequest loads in the WKWebView. I need to implement a cache. If a user presses on a tab, I'd prefer to load a cache data instead of new. Unfortunately this code doesn't work:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:0.0];
[self.webView loadRequest:request];

Can you guide me on how to implement cache for WKWebView?

like image 780
user553536 Avatar asked Jun 16 '15 10:06

user553536


People also ask

Is WKWebView the same as Safari?

WKWebView - This view allows developers to embed web content in your app. You can think of WKWebView as a stripped-down version of Safari. It is responsible to load a URL request and display the web content. WKWebView has the benefit of the Nitro JavaScript engine and offers more features.

Does WKWebView store cookies?

Starting from iOS 8, Apple has deprecated UIWebView in favor of the new powerful WKWebView . The code above has no effect with the new web view since each WKWebView instance has its own cookie storage represented by WKHTTPCookieStore class. In addition, it seems there is no public API to achieve the desired behavior.

Does Chrome use WKWebView?

In Chrome 48 we've made the switch from UIWebView to WKWebView, leading to dramatic improvements in stability, speed, responsiveness, and web compatibility.


2 Answers

If you used NSURLRequestUseProtocolCachePolicy, which is the default, there shouldn't be anything else you need to do. This policy will automatically look at the response from the server to decide whether or not it should actually go and grab the data again.

If the server uses Cache-Control HTTP headers and sets the max age for its responses, NSURLSession will respect this and return cached responses before they expire.

like image 101
Dreaming In Binary Avatar answered Oct 06 '22 00:10

Dreaming In Binary


I typically will load from a server if I have internet connectivity. Otherwise, I load from the cache.

 if reachability.isReachable {
             urlRequestCache=NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)
        }
        else {
            urlRequestCache = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60)
        }
       theWebView.loadRequest(urlRequestCache)
like image 36
Durai Amuthan.H Avatar answered Oct 05 '22 23:10

Durai Amuthan.H