azamsharp
azamsharp

Reputation: 20068

NSURLCache Images Using AFNetworking API

I have an app which is downloading images from the server. The images are approx 56 KB and there are at least 30 of them. There are times when the user either have no connection or Edge connection (Dialup).

I am using NSURLCache in my AppDelegate.h like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   
    int cacheSizeMemory = 4*1024*1024; // 4MB
    int cacheSizeDisk = 32*1024*1024; // 32MB
    NSURLCache *sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
    [NSURLCache setSharedURLCache:sharedCache]; 

But for some reason it does not cache the images. If I load all the images with internet connection available and then disconnect or use Edge network it again fetches the images.

Upvotes: 1

Views: 3514

Answers (2)

AliSoftware
AliSoftware

Reputation: 32681

Edit: iOS 5 and onwards supports disk caching if you use NSURLRequest's NSURLRequestReturnCacheDataElseLoad cachePolicy or return the appropriate Cache-Control headers.

This issue about caching is explained in the AFNetworking F.A.Q..

In summary, it seems that on iOS, NSURLCache does not provide disk cache capability, even if you create an NSURLCache with a diskCapacity>0 (it seems to be ignored), and the solution is to use some other implementation of NSURLCache like the SDURLCache suggested in the FAQ.

Upvotes: 1

Ryan Rife
Ryan Rife

Reputation: 169

You need to have access to the server to ensure that it is sending back the cache-control header for each request for the NSURLCache to be of any use. If you don't or can't get that setup (like in my scenario) you'll need to roll your own caching layer or use something like SDURLCache or RNCachingURLProtocol.

Upvotes: 0

Related Questions