I'm trying to implement HTTP caching for a WKWebView that should behave like this:
- Network available: Fetch web data from network & cache it.
- Network unavailable and has cached data: Load the cached data.
- Network unavailable and doesn't have cached data: Show a fallback error view.
First I'm using similar code like in this answer https://stackoverflow.com/a/55909771/356105 to cache data and check if data has been cached. i don't think this should be necessary for use with WKWebView but I couldn't find any better solution to check for cached data.
Then I'm using https://github.com/ashleymills/Reachability.swift to check if a network connection is available at all before trying a web view load request. If no network connection is available but there is cached data found by using downloadContent()
I'm trying a web view load after changing the cachePolicy:
var request = request
request.cachePolicy = .returnCacheDataDontLoad
_webView.load(request)
If there is no network and no cached data, I want to show my fallback view:
private func onWebViewNavigationFailed(navigation: WKNavigation!, error: Error)
{
if !_isNetworkReachable && !_hasChachedData
{
showEmptyResultView()
}
}
But this whole construct is working unreliably. With some web pages it works, with some not. When it has cached data (_hasChachedData = true
) half of the time the webview loads the cached data, the other times not at all...
So my question is: What's the proper way to implement caching with WKWebView
and how can I check if WKWebView
has cached data available for a specific request? There has been a lot of guess work because I cannot find one suitable solution on the web for this.
A rundown on how to implement this requirement properly would be very helpful.