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)
            })
            task.resume()
        } else {
            //if cache response is not nil then print
            let string = NSString(data: cacheResponse!.data, encoding: NSUTF8StringEncoding)
            println(string)

        }