【问题标题】:How to enable disk cache in AFNetworking on iOS如何在 iOS 上的 AFNetworking 中启用磁盘缓存
【发布时间】:2015-12-02 09:18:32
【问题描述】:

在我的 iOS 应用程序中,我是 AFNetworking 提供的 UIImageView 类别,用于下载存储在 Amazon S3 上的图像。我认为默认缓存默认将缓存图像存储在磁盘上,但是,由于多种原因(缺少 HTTP 标头等),我意识到我错了。图像似乎没有被缓存,它们在每次执行时都会被下载。

因此,我现在正在尝试自定义缓存,如此处建议的 http://blog.originate.com/blog/2014/02/20/afimagecache-vs-nsurlcache/

这是我到目前为止所做的(似乎有效):

1) 定义了一个名为 PlayerImageCache 的自定义 NSURLCache 并在我的应用程序委托中对其进行了初始化,以便使用 5MB 内存和最多 100MB 磁盘空间

PlayerImageCache *sharedCache = [[PlayerImageCache alloc] initWithMemoryCapacity:5*1024*1024 diskCapacity:100*1024*1024 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];

2) 重写了 storeCachedResponse 方法以便始终缓存我的图像

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse
                 forRequest:(NSURLRequest *)request
{
    if ([request.URL.absoluteString hasPrefix:playersImagesPrefix])
    {
        NSCachedURLResponse *modifiedCachedResponse = [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:cachedResponse.userInfo storagePolicy:NSURLCacheStorageAllowed];
        [super storeCachedResponse:modifiedCachedResponse forRequest:request];
    }
    else
    {
        [super storeCachedResponse:cachedResponse forRequest:request];
    }
}

3) 使用 NSURLRequestReturnCacheDataElseLoad 策略强制每个请求在下载图像之前检查缓存

NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL urlForPlayer:self.playerId] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
[self.playerImage setImageWithURLRequest:imageRequest placeholderImage:[UIImage imageNamed:@"playerprofile"] success:nil failure:nil];

这就够了吗?我是否需要进一步自定义我的缓存?即使没有 Cache-Control HTTP 标头,这也能工作吗?

【问题讨论】:

    标签: ios amazon-s3 afnetworking afnetworking-2 cache-control


    【解决方案1】:

    答案是肯定的!它就像一个魅力。由于这个技巧,我设法大大减少了请求的数量。

    【讨论】:

      猜你喜欢
      • 2014-07-03
      • 2023-04-07
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 2017-06-15
      • 2014-07-21
      • 2015-08-18
      相关资源
      最近更新 更多