iOS Development

ios – URLCache ignores `max-age` on 304 (Not Modified) responses after header manipulation

Spread the love


For the reason that sever response configuration has a not appropriate cache-control max-age header I would like to control max-age to 10 seconds with "max-age=10". I’m utilizing .useProtocolCachePolicy for the requests.

Then the next downside happens:
When receiving responses with the standing code 200, URLCache is up to date appropriately and takes max-age into consideration within the cache coverage. If the cache has expired, it additionally appropriately sends conditional requests with If-Modified-Since and If-None-Match. If the server now responds with the standing code 304 (Not Modified), it doesn’t replace the cache with the brand new response. Which means that it nonetheless regards the cached response as expired and continues to make conditional requests to the server.

The same query got here up in NSURLCache ignores `max-age` on 304 (Not Modified) responses. The supplied concept/answer didn’t work and it was meant for a legacy API.

I attempted to implement a customized URLCache to control the Cache-Management header:

override func storeCachedResponse(_ cachedResponse: CachedURLResponse, for request: URLRequest) {
    guard let httpResponse = cachedResponse.response as? HTTPURLResponse else {
        tremendous.storeCachedResponse(cachedResponse, for: request)
        return
    }
    
    let modifiedHeaders = NSMutableDictionary(dictionary: httpResponse.allHeaderFields)
    modifiedHeaders["Cache-Control"] = "max-age=10"
    
    if let url = httpResponse.url,
       let modifiedResponse = HTTPURLResponse(url: url,
                                              statusCode: httpResponse.statusCode,
                                              httpVersion: "HTTP/1.1",
                                              headerFields: modifiedHeaders as? [String: String]) {
        
        // Create a brand new CachedURLResponse with the modified HTTPURLResponse
        let modifiedCachedResponse = CachedURLResponse(response: modifiedResponse, information: cachedResponse.information, storagePolicy: cachedResponse.storagePolicy)
        
        // Retailer the modified CachedURLResponse within the cache
        tremendous.storeCachedResponse(modifiedCachedResponse, for: request)
    } else {
        tremendous.storeCachedResponse(cachedResponse, for: request)
    }
    
}

I additionally tried to control the header with the identical concept in urlSession(_:dataTask:willCacheResponse:completionHandler:) from the URLSessionDataDelegate. Each didn’t work. Did anyone run into the identical downside?

Leave a Reply

Your email address will not be published. Required fields are marked *