agandi
agandi

Reputation: 591

NSURLCache caching with different POST requests

I am using NSURLSession for networking and making POST requests to a server. I want to be able to cache these requests, however the URL is always the same.

Is it possible to cache with NSURLCache and change the cache key to something unique such as the request body?

Upvotes: 4

Views: 1012

Answers (1)

dgatwood
dgatwood

Reputation: 10417

By default, IIRC, POST requests are not cached at all. But yes, you can certainly do it. IIRC, on the NSURLSession side, the only thing you can control is whether the request gets cached or not. To actually control the name under which it is cached, you'll need to implement a custom URL protocol. I've never done what you're trying to do, but I'm pretty sure you'd do it roughly as follows:

  • Create an NSURLProtocol subclass, and provide it via the protocolClasses property on your session configuration. From that point on, your class gets called first whenever any that session makes a URL request.

  • In that subclass, in your startLoading method, use setProperty:forKey:inRequest: to tag the request as having been processed by your protocol.

  • In your canInitWithRequest method, call propertyForKey:inRequest: to see if the request is already tagged, and if so, return NO. That way, you'll see each request exactly once.

  • In your startLoading method, start a new data task with the tagged request.

  • In stopLoading, cancel the task.

  • In canonicalRequestForRequest:, do your conversion. You might have to use setProperty:forKey:inRequest: to store the original, unmodified URL, just in case you get back the modified URL. (I'm not sure.)

  • I don't think you'll need to implement requestIsCacheEquivalent:toRequest:, but keep it in mind, just in case I'm wrong. You might be able to implement that instead of the canonicalization method, also.

Upvotes: 0

Related Questions