How To Change URLSession Cache Size

When you start using some networking in your app you might think about caching requests to make your app faster.

By default cache size is 4 megabytes of memory capacity and 20 megabytes of disk.

You can change these sizes.

First, you need to create a new URLCache object with new capacities:

let cache = URLCache(memoryCapacity: 30 * 1024 * 1024, diskCapacity: 25 * 1024 * 1024, directory: nil)

30 * 1024 * 1024 is equal to 30 megabytes and 25 * 1024 * 1024 is equal to 25 megabytes.

Then if you want to use it only for a single request then you can set it as configuration to URLSession:

let configuration = URLSessionConfiguration.default
configuration.urlCache = cache
let session = URLSession(configuration: configuration)

Or if you want to use this cache for all requests:

URLCache.shared = cache