URLresponse is not retrieved after storing in cache using storeCachedResponse

Welcome to the wonderful world of asynchronous caches. NSURLCache is highly asynchronous. Just because you’ve shoved data into it doesn’t mean it is available for retrieval. You have to let the main run loop return before it will be available, and possibly even wait a little while. The failure to return a response immediately after storing it is not at all unusual. Try dispatching it after five seconds or so.

Second, your cache might be a bit on the small size for storing multi-megabyte images. Try bumping that up and see if it helps.

Finally, what do you mean when you say that you “turn off your Internet?” You say that you’re getting a timeout. Normally, if you put the device into Airplane mode with all connectivity disabled, it should not sit there for any significant amount of time before failing with an error indicating no connectivity). If that isn’t happening, something strange is happening, almost as if waitsForConnectivity is getting set on the session or something. (You aren’t making the network requests in the background, are you? If so, try explicitly setting waitsForConnectivity to NO so that they won’t wait for a connection to be available.)

Also, for this usage, you may have to strip out the Vary: Accept-Encoding header or provide a consistent user agent string. That header causes the cache to basically be per-browser. This may cause the cache to behave in unexpected ways, and is probably the cause of the weirdness you’re seeing.

Note that stripping out the Vary header is a bit of a hack, and probably isn’t the most correct way to fix the issue; ideally, you should tweak whatever outgoing header fields you have to tweak so that it works even with that header present. But you’d have to research it and figure out exactly what fields are needed, because I have no idea. 🙂

Leave a Comment