简体   繁体   中英

NSURLCache with changing Mashery “sig=XXXXXX” query item

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM