cache images to temporary storage in swift

To cache images to temporary storage in Swift, we can use the built-in URLCache class of URLSession.

main.swift
// Create a new URLCache with memory capacity of 4MB and disk capacity of 20MB
let cache = URLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)

// Set the shared URLCache to our newly created cache
URLCache.shared = cache
259 chars
6 lines

Then, when making requests with URLSession, we can use a URLSessionConfiguration object that includes the cache policy in order to enable caching for our requests.

main.swift
// Create a new URLSessionConfiguration with the default cache policy
let config = URLSessionConfiguration.default

// Set the configuration's URLCache to the shared cache we created earlier
config.urlCache = URLCache.shared

// Create a new URLSession with the configuration
let session = URLSession(configuration: config)

// Make a request using the session
let request = URLRequest(url: URL(string: "http://example.com/image.jpg")!)
let task = session.dataTask(with: request) { (data, response, error) in
    // Handle the response and data as desired
}

// Resume the task to initiate the request
task.resume()
616 chars
18 lines

With this setup, any subsequent requests for the same image (with the same URL) through our URLSession will be served from the cache rather than making a new network request.

gistlibby LogSnag