With URLSession on iOS, how do URLSession.shared, a default configuration and an ephemeral configuration differ, and which suits an incognito trip planner?
answer
- what each kind writes to disk
- singleton with no delegate
- private stores held in RAM
- invalidate to purge
basics
~20 sURLSession.shared is a fixed singleton with no delegate, using the shared cache, cookie and credential stores. A default configuration starts the same but is customisable. An ephemeral one keeps private stores in memory only, which suits an incognito planner.
solid answer
~40 s`URLSession.shared` has no configuration you can change and no session delegate; it uses the shared `URLCache`, `HTTPCookieStorage` and credential storage. A session from `URLSessionConfiguration.default` behaves much like it but lets me set timeouts, headers and caching and attach a delegate; it still uses the shared cache and cookie store by default. `URLSessionConfiguration.ephemeral` gives the session a private cache, cookie store and credential store that live in RAM and are destroyed when I invalidate the session. For an incognito trip planner I would create an ephemeral session when the planner opens and call `invalidateAndCancel()` when it closes, so nothing it fetched lands on disk or in the shared cookie store.
code
swift · 21 linesimport Foundation
final class TripPlannerClient {
private let session: URLSession
init() {
let config = URLSessionConfiguration.ephemeral
config.httpAdditionalHeaders = ["Accept": "application/json"]
session = URLSession(configuration: config)
}
func plan(_ request: URLRequest) async throws -> Data {
let (data, _) = try await session.data(for: request)
return data
}
func endIncognito() {
// Drops the session's in-memory cache, cookies and credentials.
session.invalidateAndCancel()
}
}go deeper
Know the three names, shared, default and ephemeral, and that ephemeral keeps its cache, cookies and credentials in memory instead of on disk.
Explain what each configuration uses for urlCache, cookies and credentials, that the session copies its configuration, and that invalidating an ephemeral session purges its data.
Spot the leaks in review: a private mode that still hits URLCache.shared, a per-screen session never invalidated, and a cookie that crosses features through the shared store.
Weigh how many configurations the app should own and which features genuinely need isolation, such as a private mode, rather than letting every team build its own session.
## Three ways to get a session A **`URLSession`** coordinates a group of related tasks, and almost all of its behaviour comes from the **`URLSessionConfiguration`** it was created with. There are three everyday starting points, plus the background kind used for transfers that outlive the app. | Kind | How you get it | Cache | Cookies and credentials | Delegate | |---|---|---|---|---| | Shared | `URLSession.shared` | `URLCache.shared` | shared stores | none | | Default | `URLSessionConfiguration.default` | `URLCache.shared` unless you set `urlCache` | shared stores unless you replace them | optional | | Ephemeral | `URLSessionConfiguration.ephemeral` | private, in memory | private, in memory | optional | | Background | `background(withIdentifier:)` | `nil` by default | shared stores | required | ## The shared session `URLSession.shared` is a singleton you never create. Apple's documentation lists its limits plainly: - you cannot receive data incrementally through a delegate; - you cannot significantly customise connection behaviour; - your ability to handle authentication is limited; - you cannot run background transfers while the app is not running. It is based on a default configuration and uses the shared `URLCache`, `HTTPCookieStorage` and `URLCredentialStorage`. Apple also advises against customising those shared stores to bend the shared session to a feature's needs: once you care about caches, cookies or authentication, create a default session instead. ## Default and ephemeral configurations A **default** session starts out like the shared one, but you own its configuration: `timeoutIntervalForRequest`, `httpAdditionalHeaders`, `requestCachePolicy`, `waitsForConnectivity`, `allowsCellularAccess` and the rest. Its `urlCache` is the shared cache and its cookie and credential stores are the shared ones until you replace them. An **ephemeral** session is the privacy variant. The header for `ephemeralSessionConfiguration` says the session does not store caches, credential stores or any session-related data to disk; that data lives in RAM. Three details are worth knowing: 1. The only time an ephemeral session writes to disk is when you ask it to write a URL's contents to a file, as a download task does. 2. Invalidating the session purges all of its ephemeral data automatically. 3. On iOS the in-memory cache is not purged when the app is suspended, but it may be purged when the app is terminated or the system is under memory pressure. So ephemeral does not mean "no caching": repeated requests inside one session can still be answered from its private memory cache. ## Configuration is copied at creation `URLSession(configuration:)` copies the configuration. Apple's documentation is explicit that the session ignores later changes to the configuration object you passed in. If a feature needs a different timeout or cache, you build a new configuration and a new session. Copying a configuration gives you an independent object you can modify, which is the usual way to derive variants from one base. Session and task objects behave differently: copying one of those gives you back the same object, not a new one. So the unit you vary is the configuration, and the unit you keep alive and share is the session. ## The incognito trip planner A transit app's trip planner offers an incognito mode that must leave nothing behind: no cached route responses on disk, no cookies the server set, no saved credentials. - Create one ephemeral session when the incognito planner opens and route every planner request through it. - When the planner closes, call **`invalidateAndCancel()`**, which cancels outstanding tasks and invalidates the session, purging its in-memory stores. `finishTasksAndInvalidate()` is the gentler alternative that lets running tasks complete first. - Do not use `URLSession.shared` or a default session there: their responses go to `URLCache.shared`, which writes to disk, and cookies go to the shared cookie store that every other screen sees. - If the planner downloads a file, that file is written to disk because you asked for one; delete it when the planner closes. One more lifetime rule applies to every session you create with a delegate: the session keeps a **strong reference** to its delegate until it is invalidated, so a per-screen session that is never invalidated leaks the session and its delegate until the app exits.
- A teammate sets waitsForConnectivity on a configuration after creating the session from it; what happens?Nothing changes for that session. `URLSession` copies the configuration when it is created and ignores later edits to the object you passed. To change the behaviour you build a new configuration, or copy and modify the old one, and create a new session from it.
- Why not create a fresh ephemeral session for every planner request instead of one per incognito window?Each session has its own private memory cache, so a session per request caches nothing useful, and any session created with a delegate holds that delegate strongly until it is invalidated, so forgotten sessions leak. Apple's guidance is to create as few sessions as you need and share one among parts of the app that need the same configuration.
- Is a default session's cookie store private to that session?No. For default and background configurations `httpCookieStorage` is the shared cookie storage object unless you set another one, so a cookie a server sets on one default session is visible to the shared session and to other default sessions. Only an ephemeral configuration gets a private, in-memory cookie store by default.
An ephemeral session is a whiteboard in a meeting room: everything written stays only on the board, never in the building's archive, and wiping it (invalidating the session) clears it at once, although the cleaners may also wipe it if the room is needed.
- An ephemeral session turns caching off completely
- You can assign a delegate to URLSession.shared
- Editing the configuration object later updates the session that was created from it
- An ephemeral session forgets everything as soon as the app is suspended
- A default session keeps its own private cookie store