Reputation: 6692
Is it possible to use NSURLCache
to cache responses when the URL includes a changing query item? For example, we add Mashery's required "sig=XXXXXX" query item, which changes for each request.
If not, is there a workaround?
Upvotes: 0
Views: 746
Reputation: 6692
Solved by subclassing NSURLCache
and overriding its caching methods.
In each overridden method, I remove the query item from the request prior to calling the superclass' method.
For example:
override func storeCachedResponse(cachedResponse: NSCachedURLResponse, forRequest request: NSURLRequest) {
let strippedRequest = removeQueryItemFromRequest(self.queryItemName, request: request)
if let url = strippedRequest.URL {
let response = NSURLResponse(URL: url, MIMEType: cachedResponse.response.MIMEType, expectedContentLength: Int(cachedResponse.response.expectedContentLength), textEncodingName: cachedResponse.response.textEncodingName)
let newCachedResponse = NSCachedURLResponse(response: response, data: cachedResponse.data)
super.storeCachedResponse(newCachedResponse, forRequest: strippedRequest)
}
else {
super.storeCachedResponse(cachedResponse, forRequest: request)
}
}
self.queryItemName
is a stored property passed in to a custom initializer.
Upvotes: 0