NSURLConnection on iOS doesn't try to cache ob

2019-01-24 08:12发布

问题:

Despite Apple's documentation indicating otherwise, NSURLCache on iOS doesn't do any disk (flash) caching at all. You can subclass NSURLCache to change the behaviour of the fetch and store operations to use the disk (like SDURLCache does), but due to the following severe limitations of how the cache is used and implemented, this doesn't work as well as you'd expect:

  • NSURLConnection doesn't even call storeCachedResponse:forRequest: for files over about 50KB (>= 52428 bytes, to be exact). This makes subclassing NSURLCache pointless for our use (200KB images), because it won't even get to the cache. As a result, we have to add caching manually at a level above NSURLConnection.
  • Even when one calls the NSURLCache's built-in storeCachedResponse:forRequest: manually, it only stores the response in memory if it's less than about 180KB. I tested this by calling storeCachedResponse manually and seeing that the before/after currentMemoryUsage didn't change for data lengths above about 180KB. So we have to write our own LRU memory caching too.

Has anyone else noticed these issues? Or is there something I'm missing?

FYI, I'm running iOS 4.3 in the simulator and on an iPad 2.

回答1:

I'd suggest using ASIHTTPRequest library instead of NSURLRequest:

http://allseeing-i.com/ASIHTTPRequest/How-to-use

It has a robust caching API:

http://allseeing-i.com/ASIHTTPRequest/How-to-use#using_a_download_cache



回答2:

I'm not sure how it works for a UIWebvieuw, but when you use a NSURLRequest the maximum size of the file depends on how you initialize the URLCache (initWithMemoryCapacity:(NSUInteger)memoryCapacity ...)



回答3:

I'd suggest using the three20 library and TTURLRequest. This appears to have good caching for large data sizes, since it's used for Facebook and in particular the pictures.

TTURLRequest is pretty much a drop in replacement for a NSURLRequest, so should be easy to move to, and doesn't have much dependency on the rest of Three20



回答4:

Check out my fork of AFNetworking that includes a custom class of NSURLCache that supports disk saving: https://github.com/steipete/AFNetworking/tree/disk-cache