Image Caching With AFNetworking - ios

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];

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

Related

AFNetworking 3.0 on disk image caching

Is it possible in AFNetworking to cache image on disk for more than session? For example for a week or month. In my project i used SDWebImage and AFNetworking, but few days ago i found that AFNetworking has the same functionality as SDWebImage, so a removed SDWebImage and wrote such code to store image on disk:
for ImageView
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
[imageView setImageWithURLRequest:imageRequest placeholderImage:placeholderImage success:nil failure:nil];
Download image to use in future
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
[[AFImageDownloader defaultInstance] downloadImageForURLRequest:imageRequest success:nil failure:nil];
Get downloaded image
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
UIImage *image = [[AFImageDownloader defaultInstance].imageCache imageforRequest:imageRequest withAdditionalIdentifier:nil];
But all this working only per session, after i loaded all images i turn off internet and restart my app, result - no images in cache.
Also i try to add such code in AppDelegate:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
diskCapacity:100 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
But i still can't cache images for longer than session.
(Sorry for my english)
Images are cached on disk using standard NSURLCache built in iOS, meaning that if your responses include proper cache headers, those items should end up on disk in the cache. So for example headers should look like:
"Accept-Ranges" = bytes;
"Cache-Control" = "max-age=604800";
Connection = close;
"Content-Length" = 3808;
"Content-Type" = "image/png";
Date = "Tue, 29 Mar 2016 19:55:52 GMT";
Etag = "\"5630989d-ee0\"";
Expires = "Tue, 05 Apr 2016 19:55:52 GMT";
"Last-Modified" = "Wed, 28 Oct 2015 09:42:53 GMT";
Server = nginx;
also if you have downloaded an image and want to get it from the disk cache do:
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
UIImage *image = [UIImage imageWithData:[[AFImageDownloader defaultURLCache] cachedResponseForRequest:imageRequest].data];

Local HTML Cache policy in UIWebView

I have walked through various solution to clear the local image cache in UIWebView, while i trying to load the image in html it atomically displays the previous image(i using the same name to replace the image in template).
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL fileURLWithPath:[[CustomFunctions getFilesPath] stringByAppendingPathComponent:obj]] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
[webview1 loadRequest:request];
[webview1 reload];
this is my code and can any one please suggest me to do this. Thanks in advance. sorry for my English.
//to prevent internal caching of webpages in application
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
//[sharedCache release];
sharedCache = nil;
try using this. It will clear the url cache memory of your application.
Try this ...
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];
This would remove a cached response for a specific request. There is also a call that will remove all cached responses for all requests ran on the UIWebView:
[[NSURLCache sharedURLCache] removeAllCachedResponses];

NSURLCache is emptied when app is closed

i'm trying to implement a NSURLCache with AFHTTPRequestOperation, this is what i have done:
AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:50 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];
....
}
Then to use it i do this:
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0f];
UIImage *image = [[UIImageView sharedImageCache] cachedImageForRequest:urlRequest];
if (image != nil) {
//Cached image
} else {
AFHTTPRequestOperation *postOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
postOperation.responseSerializer = [AFImageResponseSerializer serializer];
[postOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
UIImage *image = responseObject;
[[UIImageView sharedImageCache] cacheImage:image forRequest:urlRequest];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image error: %#", error);
}];
[postOperation start];
}
the first time i open the view when there is the code above download the image and store it in the cache, then i close the view and i open it again and read it from the cache, instead if i close the app, and i try again the image is downloaded again, so how i can create a NSURLCache persistent?
EDIT:
I have tried what Duncan Bubbage suggest, and i have add a cache path instead of the nil, and i have do it in this way:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
cachePath = [cachePath stringByAppendingPathComponent:#"temp_img"];
NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:50 * 1024 * 1024 diskPath:cachePath];
[NSURLCache setSharedURLCache:URLCache];
but i still cannot cache perstitently across session, what i have wrong? i have also check in the Finder the Cache Folder, and there is the temp_img folder, i have tried to create the folder manually with NSFileManager and then pass the path, but the folder temp_img remain empty...
Are you sure it is valid to set diskPath:nil when you are wanting to cache to disk persistently across sessions? The parameter is optional but that may only be for the use case of caching in memory only, in which case you'd expect to see what you're seeing here?
Alternatively, the Apple documentation for this method states:
NOTE
In iOS, the on-disk cache may be purged when the system runs low on disk space, but only when your app is not running.
This could just be expected behaviour?

NSURLCache not used by NSURLConnection / AFNetworkingOperation

When I start a request with the NSURLRequestReturnCacheDataElseLoad policy I expect to get the result from the NSURLCache if any, no matter how old it is. However, the system always tries to reach the server the request points to and returns an error if the server doesn't answer.
I use the UIImageView category of AFNetworking for the request.
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
__weak __typeof(self) weakSelf = self;
NSLog(#"[%#] %#", request.URL, [[NSURLCache sharedURLCache] cachedResponseForRequest:request]); // this returns an instance of NSCachedURLResponse!
[self setImageWithURLRequest:request placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
__typeof(weakSelf) self = weakSelf;
self.image = image;
} failure:NULL];
This will not set the image even if asking the NSURLCache directly will return a valid NSCachedURLResponse.
The app is running on iOS6 only, so there should be no problems with on-disk cache as far as I know?!
Any help is appreciated! Thanks!
This is a know issue. Please refer this discussion on AFNetworking github page for a workaround.

NSXMLParser Cache

I'm developing an application that uses the xml parsing. Everything works wing perfection but when I edit the xml file changes are not displayed. I think it may be a matter of cache because the file is loaded correctly on the server. how do I fix it?
-(IBAction)avviaParsing{
NSString *urlstring=#"http://www.acicastelloonline.it/app_ios/show.xml";
NSURL *xmlURL=[NSURL URLWithString:urlstring];
NSXMLParser *parser = [[ NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[parser setDelegate:self];
[parser parse];
[parser release];}
here is three option, you should try this code before XMLParsing:
you select only one of the three.
clearing
[[NSURLCache sharedURLCache] removeAllCachedResponses];
disable cache
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:cache];
[sharedCache release];
this is other solution.
NSURL *xmlURL=[NSURL URLWithString:URL];
NSURLRequest *request = [NSURLRequest requestWithURL:xmlURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:0.0f];
NSXMLParser *xmlParser =[[NSXMLParser alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

Resources