Search code examples
iosobjective-ccachingafnetworking-2

Image Caching With AFNetworking


The cache mechanism of AFNetworking is not working for me, I have an image of 500ko with big dimension and I want to cache it. But every time I close the application and open it again I have to wait for 20sec for the image to load so the cache system is not working here is the code:

I tried :

[imageView setImageWithURL:[NSURL URLWithString:imageURL]
      placeholderImage:[UIImage imageNamed:@"placeholder"]];

and then tried :

NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]
                                          cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                      timeoutInterval:60];

[imageView setImageWithURLRequest:imageRequest
             placeholderImage:[UIImage imageNamed:@"placeholder"]
                      success:nil
                      failure:nil];

Solution

  • NSURLCache does not write to disk in its default so we need to declare a shared NSURLCache in app delegate :

    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
                                              diskCapacity:100 * 1024 * 1024
                                              diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    

    Reference