How To Clear Image cache or any cache in AFNetworking?

后端 未结 5 1532
半阙折子戏
半阙折子戏 2021-02-06 00:30

Hi All can any one help me out how to clear the cache in AFNetworking.

I used to have old version of AFNetworking and i see that it has been updated, Can any body help m

5条回答
  •  北海茫月
    2021-02-06 00:58

    If you're using AFNetworking, I recently implemented a little workaround to remove the image from the cache.

    Look in the file "UIImageView+AFNetworking.h"

    Under @interface UIImageView (AFNetworking), add the following:

    - (void)clearImageCacheForURL:(NSURL *)url;

    And Under @protocol AFImageCache, add:

    - (void)clearCachedRequest:(NSURLRequest *)request;

    Next, open "UIImageView+AFNetworking.m"

    Under @implementation UIImageView (AFNetworking), add the following:

    - (void)clearImageCacheForURL:(NSURL *)url {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
    
        UIImage *cachedImage = [[[self class] sharedImageCache] cachedImageForRequest:request];
        if (cachedImage) {
            [[[self class] sharedImageCache] clearCachedRequest:request];
        }
    }
    

    Almost done! Now just add the following below @implementation AFImageCache:

    - (void)clearCachedRequest:(NSURLRequest *)request {
        if (request) {
            [self removeObjectForKey:AFImageCacheKeyFromURLRequest(request)];
        }
    }
    

    And you're good to go! Now when you need to clear a particular image url from the cache, just call [imageView clearImageCacheForURL:imgURL];

提交回复
热议问题