NSURLCache does not cache
I am using Xcode 6.1 (6A1030), both iOS7 and iOS8.
NSURLCache doesn't seem to cache anything. I am using the "Cache-Control" header. My server returns a Cache-Control header with "max-age = 6000".
In this example, I am breaking a request from google that 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 caching 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 answer 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 zero each time, and a new server request is sent each time.
Am I doing something wrong? Many thanks for your help!
source to share
No one has answered this question yet
See similar questions:
or similar: