【问题标题】:Images are not removed from disk after clearing cache AFNetworking清除缓存后图像不会从磁盘中删除 AFNetworking
【发布时间】:2016-11-23 02:06:47
【问题描述】:

我试图清除缓存位,应用程序的大小并没有显着变小。

我的应用程序大小约为 30MB 加上 45MB 用于缓存图像。

这就是我尝试清除缓存的方式:

 [[NSURLCache sharedURLCache] removeAllCachedResponses];
 [[AFImageDownloader defaultURLCache] removeAllCachedResponses];
 AFAutoPurgingImageCache *imageCache = [AFImageDownloader defaultInstance].imageCache;
 [imageCache removeAllImages];            
  • 在我的 iPhone 6 iOS10 上,应用程序的大小并没有变小。
  • 在模拟器中的应用程序文件com.alamofire.imagedownloader/fsCachedData 中,所有文件仍然存在

这是我使用 AFNetworking (3.1.0) 下载图像的方式:

#import "AFImageDownloader.h"

[photoImageView setImageWithURLRequest:[NSURLRequest requestWithURL:thumb] placeholderImage:myCachedImage success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                [self setPhotoImage:image];
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                [self setupPlaceholder];
            }];

【问题讨论】:

  • 我发现缓存并不总是在模拟器中工作,尝试真实设备。

标签: ios afnetworking


【解决方案1】:

见下文:

  1. AFAutoPurgingImageCache *imageCache = [AFImageDownloader defaultInstance].imageCache;imageCache存储在内存中,做[imageCache removeAllImages];没用
  2. 你只需要[[AFImageDownloader defaultURLCache] removeAllCachedResponses];。它是苹果提供的唯一用于清除 URLCache 的 API。
  3. 当您调用removeAllCachedResponses 时,您会发现fsCachedData 未被删除。这是因为苹果有自己的机制来清除磁盘数据。也许它会在我搜索时每7天清除一次磁盘数据,但我不能确定。
  4. 我认为看看其他人如何使用fsCachedData 很有趣。 Should I clear the fsCachedData folder myself?
  5. 希望对您有所帮助。

【讨论】:

  • 任何解决方案,因为我每次下载图像时都面临同样的问题。只希望应用程序每次都从同一个 URL 下载图像。任何帮助将不胜感激。
【解决方案2】:

我们也在我们的一款应用中看到了这一点。根据http://blog.airsource.co.uk/2014/10/11/nsurlcache-ios8-broken/,这是一个 iOS 8 错误,Apple 将在今天的 iOS 8.1 更新中纠正。

所以回答你的问题:不,你不应该自己删除缓存,如果运气好的话,Apple 的修复程序真的会清理旧数据。如果由于某种原因没有,您应该可以自己删除它而不会出现任何问题。

我已经验证 iOS 8.1 确实纠正了这个问题。然而,用户必须在更新后启动应用程序才能清除缓存。

【讨论】:

  • 你为什么要谈论 iOS 8,并链接到 2014 年的一篇博文?我们现在是 2016 年,大多数人都在使用 iOS 10。我遇到了与原始海报相同的问题,但我怀疑这与 iOS 8 中的错误有关(在 iOS8.1 中已修复)。
【解决方案3】:

此代码适用于 AFNetworking 3.1:

        [[NSURLCache sharedURLCache] removeAllCachedResponses];

        AFImageDownloader *imageDownloader = [AFImageDownloader defaultInstance];
        NSURLCache *urlCache = imageDownloader.sessionManager.session.configuration.URLCache;
        [urlCache removeAllCachedResponses];

        [imageDownloader.imageCache removeAllImages];

【讨论】: