NSURLCache with changing Mashery "sig=XXXXXX" query item

737 views Asked by At

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?

1

There are 1 answers

0
Marco On

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.