URLSessionConfiguration

Networking Mid-level Swift 5.0+ iOS 15+ Reviewed By Alok Singh

Pick the fix

A sign-in flow must not leave cookies, caches or credentials on disk. Which configuration?

Options
Hint 1 of 1

Which one keeps nothing on disk?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A URLSessionConfiguration.ephemeral

Correct. Everything stays in memory and is discarded with the session.

Why not the others?
  • B .default with a short timeout. Default still persists caches and cookies.
  • C .background(withIdentifier:). Background sessions are for long transfers, not privacy.
  • D URLSession.shared. The shared session uses the shared, persistent stores.

30-second answer

.default uses disk caches and the shared cookie and credential stores. .ephemeral keeps everything in memory and discards it when the session ends, which suits private or sign-in flows. .background(withIdentifier:) hands transfers to the system so they continue while the app is suspended. Customize timeouts, headers, cache policy, cellular access and connection limits per session.

Practise saying it · 30 s. No recording, just a timer

Compare URLSession configurations.

Say your answer out loud, then check which of these points you covered:

  • default, ephemeral, background
  • Per-session tuning
  • Reuse sessions

Deep dive

waitsForConnectivity = true waits for a network instead of failing at once.

Set allowsExpensiveNetworkAccess / allowsConstrainedNetworkAccess for Low Data Mode.

Create sessions once and reuse them; each has its own connection pool.

Background sessions require delegate-based APIs.

Common mistakes

  • Creating a new URLSession per request.
  • Using the shared session for background transfers.

Senior take & follow-ups

Seniors choose the configuration by data sensitivity and transfer lifetime.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does waitsForConnectivity do?

    Show hint

    Waits for a connection instead of failing immediately.

  2. Why reuse sessions?

    Show hint

    Connection reuse and HTTP/2 multiplexing.

Suggest a fix if something here is wrong or out of date.