Cache for WKWebView
Asked Answered
H

2

15

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?

Honghonied answered 16/6, 2015 at 10:22 Comment(0)
R
12

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.

Retention answered 25/6, 2015 at 23:26 Comment(1)
Wondering if this will work when there is no internet connection. That is what happens with UIWebView. not sure about WKWebView.Longlongan
W
5

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)
Westerfield answered 28/1, 2016 at 9:4 Comment(3)
This doesn't work for WKWebView, as mentioned here, forums.developer.apple.com/thread/53573.Andrew
@Andrew - I have tried it myself before year and it was working fine in wkwebviewWesterfield
@DuraiAmuthan.H did you try it with WKWebView and turning the internet connection off?Longlongan

© 2022 - 2024 — McMap. All rights reserved.