How do I get cached image stored by AFNetworking&#

2019-08-27 21:34发布

问题:

I'm using following category UIImageView+AFNetworking.h from AFNetworking in my app, its working fine, its caching photos for me and loads images smoothly.

At one point, I want to get an image which is already there in my cache.

So I dig up into above category class where I found following code, which I think – can be helpful.

Here's the snippet from it:

@implementation AFImageCache

- (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
    switch ([request cachePolicy]) {
        case NSURLRequestReloadIgnoringCacheData:
        case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
            return nil;
        default:
            break;
    }

    return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
}

- (void)cacheImage:(UIImage *)image
        forRequest:(NSURLRequest *)request
{
    if (image && request) {
        [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
    }
}

@end

If you want me to add web version of this, it's already here.

I think, - (UIImage *)cachedImageForRequest:(NSURLRequest *)request is the method which can return me my cached image.

But I'm not sure, how can I use it?

If I know Objective-C a bit, it's a kinda a "protocol"?

What I have tried so far is to use it like a protocol in one of my view controller. Like this:

#import <UIKit/UIKit.h>

@interface MyViewController : UIViewController<AFImageCache>

@end

But then it is giving me following warnings:

I'm not sure how to resolve those warnings and get the image from cache? Or any other more appropriate way?

回答1:

I assume you import UIImageView+AFNetworking.h header.

If you want to access to the cached image. You should have a NSURLRequest object. Then it is like this:

UIImage *image = [[UIImageView sharedImageCache] cachedImageForRequest:request];

Done!