skip to content

With URLSession, how do you set URLCache and URLRequest.CachePolicy so a transit app's live departures are never stale while its timetable still loads offline?

level: middleimportance: should knowfreq 52%

answer

  1. session default versus per-request policy
  2. regardless of age or expiration
  3. a cache the system may purge
  4. willCacheResponse to veto storage

basics

~10 s

Give live-departure requests cachePolicy .reloadIgnoringLocalCacheData so URLCache never answers them, and give timetable requests .returnCacheDataElseLoad. URLCache can be purged, so a timetable that must work offline belongs in a downloaded file.

solid answer

~40 s

A session's `URLSessionConfiguration` holds a `urlCache` and a `requestCachePolicy`, which defaults to `.useProtocolCachePolicy`, so the cache follows HTTP's own rules. When live departures look old, the usual causes are a server response that allowed caching or a cache-first policy someone set session-wide. I fix it per request: live calls get `.reloadIgnoringLocalCacheData`, which never answers from the local cache, and timetable calls get `.returnCacheDataElseLoad`, which returns any cached copy regardless of age and goes to the network only if none exists. I would not rely on `URLCache` for a timetable that must work offline next week: on iOS its disk cache can be purged when space runs low, and caching any given response is not guaranteed, so offline packs should be downloaded files.

code

swift · 28 lines
swift
import Foundation

let timetableCache = URLCache(memoryCapacity: 8 * 1024 * 1024,
                              diskCapacity: 100 * 1024 * 1024,
                              directory: nil)

func makeTransitSession() -> URLSession {
    let config = URLSessionConfiguration.default
    config.urlCache = timetableCache
    // Every request inherits this unless it sets its own policy.
    config.requestCachePolicy = .useProtocolCachePolicy
    return URLSession(configuration: config)
}

func liveDepartures(stop: URL, session: URLSession) async throws -> Data {
    var request = URLRequest(url: stop)
    // Live data: never answer from the local cache.
    request.cachePolicy = .reloadIgnoringLocalCacheData
    let (data, _) = try await session.data(for: request)
    return data
}

func offlineTimetable(url: URL, session: URLSession) async throws -> Data {
    // Any cached copy, whatever its age; the network only if none exists.
    let request = URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad)
    let (data, _) = try await session.data(for: request)
    return data
}

go deeper

for a junior

Recall that URLRequest has a cachePolicy, that useProtocolCachePolicy is the default, and that reloadIgnoringLocalCacheData skips the local cache.

for a middle

Explain how urlCache and requestCachePolicy on the configuration combine with a per-request policy, and what each policy does when the cached copy is old or missing.

for a senior

Diagnose a stale screen by checking the session-wide policy, the response's cacheability and leftover cached entries, and argue why offline data belongs in owned files.

for a principal

Decide who sizes and clears each cache, which features may cache at all, and how sign-out wipes every store the app's sessions share.

## The pieces: a cache and a policy **`URLCache`** maps requests to **`CachedURLResponse`** objects and keeps them in a composite cache with a memory part and a disk part. A session finds its cache through `URLSessionConfiguration.urlCache`: - a **default** configuration uses `URLCache.shared`, which, unless you replace it, is created with 4 MB of memory capacity and 20 MB of disk capacity in the app's Caches directory; - an **ephemeral** configuration gets a private in-memory cache; - a **background** configuration has no cache (`nil`); - setting `urlCache = nil` disables caching for that session. You can create a cache with your own sizes and directory with `URLCache(memoryCapacity:diskCapacity:directory:)`, available from iOS 13; the older `diskPath:` initialiser is marked to be deprecated in its favour. The **policy** decides whether a request may be answered from that cache. `URLSessionConfiguration.requestCachePolicy` is the default every request in the session inherits, and it starts as `.useProtocolCachePolicy`. A single `URLRequest` can carry its own `cachePolicy`; Apple's configuration documentation notes that a policy set on the request is respected unless the session's policy is more restrictive. ## The policies | `URLRequest.CachePolicy` | Local cache | Network | |---|---|---| | `.useProtocolCachePolicy` | follows the protocol's caching rules | as those rules require | | `.reloadIgnoringLocalCacheData` | ignored | always | | `.returnCacheDataElseLoad` | used regardless of age or expiration | only if nothing is cached | | `.returnCacheDataDontLoad` | used regardless of age or expiration | never; the load fails if nothing is cached | | `.reloadRevalidatingCacheData` | used if the origin confirms it is still valid | otherwise loads | For HTTP and HTTPS, `.useProtocolCachePolicy` means the response's caching headers decide freshness and revalidation. Those header semantics are covered in the lesson on HTTP caching and conditional requests; from URLSession's side, what matters is that the server's headers can make a response cacheable even when the screen wants live data. Apple also notes that this default policy caches HTTPS responses to disk. ## Diagnosing the stale departures board A transit app refreshes its departures every few seconds, yet the board shows the same minutes-old times. The usual causes, in the order to check them: 1. **A session-wide cache-first policy.** Someone set `requestCachePolicy = .returnCacheDataElseLoad` on the shared configuration so timetables would work offline. Every departures request is now answered from cache, whatever its age. 2. **A cacheable live response.** With `.useProtocolCachePolicy`, the server's response allows caching, so repeated requests within the freshness window never reach the network. 3. **A cached copy from an earlier build.** The policy was fixed but the old cached response is still on disk; `removeCachedResponse(for:)` or `removeAllCachedResponses()` clears it. The fix belongs on the request, not in a global setting: live departures and vehicle positions use `.reloadIgnoringLocalCacheData`, or travel on a session whose `urlCache` is `nil`. ```swift func liveDepartures(stop: URL, session: URLSession) async throws -> Data { var request = URLRequest(url: stop) request.cachePolicy = .reloadIgnoringLocalCacheData let (data, _) = try await session.data(for: request) return data } ``` ## Why the offline timetable should not live in URLCache `.returnCacheDataElseLoad` and `.returnCacheDataDontLoad` look like an offline mode, and the header comment even calls the second one similar to an offline mode. They are fine for showing the last timetable while the network is slow. They are a poor guarantee for "works offline next week": - `URLCache`'s documentation says that on iOS the on-disk cache may be purged when the system runs low on disk space, though only while the app is not running. - The data delegate's `willCacheResponse` documentation says there is no guarantee that caching will be attempted for a given resource. - Cache capacity is bounded, so large packs can push each other out. Data the app must have belongs in files it downloads and owns, for example a download task's file moved into Application Support. ## Controlling what gets stored Per response, `URLSessionDataDelegate`'s **`urlSession(_:dataTask:willCacheResponse:completionHandler:)`** lets you pass the proposed response through, pass `nil` to prevent caching, or pass a copy with `storagePolicy` `.allowedInMemoryOnly`. Apple's article on cached data says it is called only for data and upload tasks, and not for sessions with a background or ephemeral configuration. You can also work with the cache directly: - `cachedResponse(for:)` returns the stored `CachedURLResponse` for a request, or `nil`; - `storeCachedResponse(_:for:)` writes one yourself; - `removeCachedResponse(for:)`, `removeCachedResponses(since:)` and `removeAllCachedResponses()` delete one entry, recent entries, or everything; - `currentDiskUsage` and `currentMemoryUsage` show how full each part is against `diskCapacity` and `memoryCapacity`.

  • How do you stop responses that contain personal trip history from being written to disk?
    Implement `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and pass `nil` to refuse caching, or a new `CachedURLResponse` with `storagePolicy` `.allowedInMemoryOnly`. Alternatively send those requests through an ephemeral session, whose private cache never touches disk.
  • The user signs out; how do you clear what URLSession cached for them?
    Call `removeAllCachedResponses()` on every `URLCache` the app's sessions use, `URLCache.shared` included if a default session relies on it, and clear the cookie and credential stores those sessions share. Invalidating an ephemeral session purges its private stores on its own.

  • returnCacheDataElseLoad only returns responses that are still fresh
  • URLCache keeps a response until the app removes it
  • A URLRequest's cachePolicy is ignored once the session sets requestCachePolicy
  • willCacheResponse is called for every task in every kind of session
  • useProtocolCachePolicy never stores HTTPS responses on disk