NetworkingMidMCQ

What is `URLCache` and how does caching work in iOS?

Test your knowledge:

Explanation & Code

Answer: URLCache stores responses from network requests in memory and/or on disk. It respects HTTP cache headers (Cache-Control, ETag, Expires) automatically.

Code Example:

// Configure a larger cache at app startup
URLCache.shared = URLCache(
    memoryCapacity: 50 * 1024 * 1024,  // 50MB memory
    diskCapacity: 200 * 1024 * 1024,   // 200MB disk
    directory: nil
)

// Control caching per request
var request = URLRequest(url: url)
request.cachePolicy = .returnCacheDataElseLoad  // use cache, fall back to network

// Cache policies:
// .useProtocolCachePolicy     — default, follows HTTP headers
// .reloadIgnoringLocalCache   — always hits network
// .returnCacheDataElseLoad    — use cache, only fetch if not cached
// .returnCacheDataDontLoad    — only use cache, never fetch (offline mode)

// Manually store a response
let cachedResponse = CachedURLResponse(response: response, data: data)
URLCache.shared.storeCachedResponse(cachedResponse, for: request)

Rate your understanding:

Ready to practice more Networking?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.