Wednesday, May 20, 2015

Swift: URL response caching using NSURLCache.

Download XCode project

//Create request with caching policy
let request = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60)
//Get cache response using request object
let cacheResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
//check if cached response is available if nil then hit url for data
if cacheResponse == nil {

            //default configuration
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()

            //Enable url cache in session configuration and assign capacity
            config.URLCache = NSURLCache.sharedURLCache()
            config.URLCache = NSURLCache(memoryCapacity: 51200, diskCapacity: 10000, diskPath: "urlCache")
            //create session with configration
            let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
            //create data task to download data and having completion handler
            let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
                //below two lines will cache the data, request object as key
                let cacheResponse = NSCachedURLResponse(response: response, data: data)
                NSURLCache.sharedURLCache().storeCachedResponse(cacheResponse, forRequest: request)
        } else {
            //if cache response is not nil then print
            let string = NSString(data: cacheResponse!.data, encoding: NSUTF8StringEncoding)



  1. Many thanks, Dilip. For some reason there are lots of instructions about making responses to never cache, but it is almost impossible to find how to force caching when it is explicitly says "no-cache" in "Cache-Control". Your example helped me a lot.

  2. Hello Dear
    Help me how to catch the data and reload after every 3 min. in catch data and remove every 24 hours