URLCache selective purge by age or URL pattern for mutable responses
0 reputation · 30 Aug 2025, 00:34 UTC
0 reputation · 30 Aug 2025, 00:34 UTC
Foundation's URLCache stores CachedURLResponse objects and consults them according to the request's CachePolicy, but the cache object itself does not compute HTTP freshness. For mutable resources lacking strong validators, useProtocolCachePolicy can reuse a stored response until the policy marks it stale, while reloadIgnoringLocalCacheData forces a new load. The class exposes removeCachedResponse(for:) and removeAllCachedResponses(), yet there is no documented predicate to evict entries by age, URL pattern, session, or tag; memoryCapacity and diskCapacity are storage limits rather than freshness rules.
When a server body changes without an ETag or short max-age, what boundary should an application observe before treating a cached response as invalid? Is the intended contract that clients must attach validators server-side, rely on reloadIgnoringLocalCacheData for critical reads, or subclass URLCache to add selective eviction? Which behavior is stable across supported OS versions when disk persistence makes results appear stale across app launches?
35775 reputation · 30 Aug 2025, 08:59 UTC
When a server returns a mutable response without an ETag or a short max‑age, the cache cannot rely on a server‑provided validator to decide freshness. The only reliable boundary is the response’s timestamp (the Date header) together with any freshness header the server may send, such as Last‑Modified or Expires. If none of those are present, the application must treat the cached object as valid only until the elapsed time exceeds a reasonable limit, or it must force a fresh fetch by using reloadIgnoringLocalCacheData for critical reads.
URLCache does not compute HTTP freshness itself; it only respects the CachePolicy and the response’s timestamps. The public API offers removeCachedResponse(for:) and removeAllCachedResponses(), but no predicate for age, URL pattern, session, or tag, and memory or disk capacity limits are storage constraints, not freshness rules. Selective eviction therefore requires a custom subclass that overrides the removal logic while preserving the cache’s capacity management.
Date header and compare it to the current time.URLCache and override removeCachedResponse(for:) to inspect the URL and age, then call super.removeCachedResponse.Please let me know if the server supplies any freshness header (e.g., Last‑Modified, Expires, Cache‑Control) that can be used to determine staleness.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.