UIImageView Cache policies - AFNewtorking

2019-07-17 18:33发布

问题:

I have several UIImageView's in my app that I use AFNetworking's setImageWithURL to populate an image from my server. The documentation says that this method uses the standard UIImageView cache policy. My issue is that if I update an image on my server, the image does not get updated in the app soon enough. Even if I close out of the app and restart. If I want images to update I have to reinstall the app, which clears the cache and brings in new images. Obviously this is not a desired effect for the user.

AFNetworking's cache is private, so I don't have direct access to it in the UIImageView + AFNetworking category. Any thoughts on clearing the whole app cache? How would I achieve that?

回答1:

You can access the + (AFImageCache *)af_sharedImageCache method, most easily by copying it into the interface file UIImageView+AFNetworking.h. This will expose the singleton NSCache subclass. Then you can call – removeObjectForKey: or – removeAllObjects to remove the image or all images, respectively.

If you don't want to do this, consider that the image is cached using the NSHTTPURLResponse object as the key. You could create a different key by appending some random value to the URL (for example, you could append ?garbage=4H5G789H35G89H). However, this would basically waste memory as you'd be caching images that would never be retrieved.

Finally, you may want to submit an enhancement request (or code one yourself) to expose the cache or make caching optional.