I am trying to solve 2 things in my UIWebView
:
- Load local assets in place of remote ones, under the right conditions
- Load remote assets as normal if there are no local ones or they are outdated
- Allow the webview to go "back" without needing to reload it's html form the server
So to handle #1 and #2, I implemented a custom subclass NSURLCache
. It gets called when the webview requests assets, and I can send along the local ones instead, aborting the server call for the asset. I even have a little timestamping system that knows if the local version is old or not to figure out which one to use.
But #3 is throwing me for a loop. It seems that regardless of cache-control headers, UIWebView
will ALWAYS reload the HTML when going back.
So I tried to force caching of the HTML in my custom NSURLCache
class. It seems to work, and returns the instance of NSCachedURLResponse
with the HTML I want, but the UIWebView
fails to notice and loads it from the server anyway. After some searching I see there is some "inconsistencies" with UIWebView
and the url cache, and I guess this is one. Works great for assets, but not so great for the HTML that makes up the page it's trying to display.
So then I decided that since this may not work, do it manually. I created a stack of urls, and their data that I fetch manually and load it with loadData:MIMEType:textEncodingName:baseURL:
. Lo and behold it seemed to work great! I could now go back, the web view delegate would intercept the load, and tell it to load my manually fetched data instead, and the server would not be hit.
However, then I noticed that the NSURLCache was no longer being used for my assets. It seems it only asks for cached assets if you load content with loadRequest:
and not by loading data or an html string with the baseUrl
set properly.
So despite all my efforts I cannot make a web view conditionally load local assets AND navigate back without hitting the server. It seems like I have a few bugs here in the SDK.
UIWebView
ignores the serversCache-Control
header for HTML contentUIWebView
asks for aNSCachedURLResponse
's for the main HTML request but is then ignored and discarded.UIWebView
asks theNSURLCache
for assets if you load it up with a request, but when loading with HTML or data it bypasses the cache completely and requests it directly from the remote server.
So first up, anyone see a solution to these things? And second, any reason that I am being stupid and these are not actually SDK bugs?