How do I get cached image stored by AFNetworking's UIImageView category?

廉价感情. 提交于 2019-12-12 04:16:40

问题


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!



来源:https://stackoverflow.com/questions/33583334/how-do-i-get-cached-image-stored-by-afnetworkings-uiimageview-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!