I'm using Xcode 6.1 (6A1030), both iOS7 & iOS8 Simulators.
NSURLCache does not seem to cache anything. I use the "Cache-Control" header. My server returns the Cache-Control header with 'max-age=6000'.
In this example, I tamper a request from Google, which is also not cached:
AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var URLCache = NSURLCache(memoryCapacity: 500 * 1024 * 1024, diskCapacity: 500 * 1024 * 1024, diskPath: "bla")
NSURLCache.setSharedURLCache(URLCache)
sleep(1)
return true
}
Then I start the connection:
let urlPath: String = "http://www.google.com"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5000)
var cachedURLResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
// cachedURLResponse is always nil
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
And before the caching of the response, I add the Cache-Control header:
func connection(connection: NSURLConnection, willCacheResponse cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse? {
var HTTPResponse = cachedResponse.response as NSHTTPURLResponse
var modifiedHeaders = NSMutableDictionary(dictionary: HTTPResponse.allHeaderFields)
modifiedHeaders["Cache-Control"] = "max-age=6000"
modifiedHeaders.removeObjectForKey("Expires")
var modifiedResponse = NSHTTPURLResponse(URL: HTTPResponse.URL!, statusCode: HTTPResponse.statusCode, HTTPVersion: "HTTP/1.1", headerFields: modifiedHeaders)
return NSCachedURLResponse(response: modifiedResponse!, data: cachedResponse.data, userInfo: cachedResponse.userInfo, storagePolicy: cachedResponse.storagePolicy)
}
The modified response looks like this:
{ URL: http://www.google.com/?gfe_rd=cr&ei=MSBGVKe7AeeI8QepoYGgCg } { status code: 200, headers { "Alternate-Protocol" = "80:quic,p=0.01"; "Cache-Control" = "max-age=6000"; "Content-Type" = "text/html; charset=windows-1255"; Date = "Tue, 21 Oct 2014 08:58:25 GMT"; Server = gws; "Transfer-Encoding" = Identity; "X-Frame-Options" = SAMEORIGIN; "X-XSS-Protection" = "1; mode=block"; } }
And yet, 'cachedResponseForRequest' returns nil every time, and a new server request is sent every time.
Am I doing something wrong? Thanks a lot for your help!