Search code examples
iosswiftcocoaswift2nsurlcache

NSURLSession and image cache


In my iOS 9+ Swift 2.2 application, I'm downloading multiple images with NSURLSession's dataWithRequest method :

    let session: NSURLSession = NSURLSession(configuration: self.configuration)
    let request = NSURLRequest(URL: self.url)
    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) in
        // Handle image
    }

    dataTask.resume()
    session.finishTasksAndInvalidate()

The question is : How can I limit the image cache size? I can see that my application is using more and more disk space on my device. Is there any way to keep the image cache but to limit the size that my application can use? Is there an expiration by default?


Solution

  • NSURLSession uses shared NSURLCache to cache responses. If you want to limit disk/memory usage of a shared cache you should create a new cache and set it as a default one:

    let URLCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
    NSURLCache.setSharedURLCache(URLCache)
    

    You could find a little more about caching here.