Search code examples
swiftnsurlcachealamofire

Alamofire - NSURLCache is not working?


I set my cache as below

var cacheSizeMemory = 20 * 1024 * 1024
var cacheSizeDisk = 100 * 1024 * 1024
var sharedCache = NSURLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "SOME_PATH")
NSURLCache.setSharedURLCache(sharedCache)

Create request with cache policy

var request = NSMutableURLRequest(URL: NSURL(string: "\(baseUrl!)\(path)")!, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: timeout)

Make a request and get a response with following Cache-Control private, max-age=60

Then try to check the cache

var cachedResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(urlRequest)

value is nil

Any thoughts?


Solution

  • I ended up manually adding Cache-Control as private in the header of my request and it now works. Don't even need to manually check the cache, Alamofire does it for you

    let cachePolicy: NSURLRequestCachePolicy = isReachable() ? .ReloadIgnoringLocalCacheData : .ReturnCacheDataElseLoad
    
    var request = NSMutableURLRequest(URL: NSURL(string: "\(baseUrl!)\(path)")!, cachePolicy: cachePolicy, timeoutInterval: timeout)
    
    request.addValue("private", forHTTPHeaderField: "Cache-Control")
    
    var alamoRequest = Manager.sharedInstance.request(urlRequest)