我希望有人能阐明一些我一直在研究但没有取得太大进展的事情。
我想利用 NSURLCache 为我在 iOS 应用程序中进行的 API 调用返回缓存的响应。当设备在线时,如果它足够新,我想返回缓存的响应,否则从远程获取。当设备离线时,我想立即返回缓存的响应(如果有的话),不管它的年龄如何。
我正在使用 AFNetworking
。我正在进行的 API 调用是针对我控制的服务器的。协议(protocol)是 HTTPS。 Cache-Control
响应 header 当前为 "max-age=0, public"
。我目前没有设置与缓存相关的请求 header (应该吗?)。我在离线时将请求的缓存策略设置为 NSURLRequestReturnCacheDataDontLoad
,在线时使用默认的 NSURLRequestUseProtocolCachePolicy
。我可以在磁盘上的默认 Cache.db
中看到请求及其响应。但是,当我处于离线状态时,所有请求都会失败(没有缓存的响应(尽管看起来已被缓存)正在使用/返回。
根据 http://nshipster.com/nsurlcache/我在 didFinishLaunchingWithOptions
中初始化了一个 sharedURLCache
并将 AFNetworking setCacheResponse
block 设置为如下所示:
NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy]; NSMutableData *mutableData = [[cachedResponse data] mutableCopy]; NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowed; return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response] data:mutableData userInfo:mutableUserInfo storagePolicy:storagePolicy];
我已经阅读了关于该主题的这些和其他帖子:
http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/ http://blackpixel.com/blog/2012/05/caching-and-nsurlconnection.html
我想知道是否有人在使用标准 NSURLCache
之前成功实现了此功能(也对涉及 SDURLCache
的成功案例感兴趣,但 Peter S. 说截至支持 iOS5 磁盘缓存,因此不再需要 SDURLCache
,即我想使用默认的内置缓存)。
提前致谢!
最佳答案
你看到这篇文章了吗?
AFNetworking (AFHttpClient) offline mode not working with NSURLRequestReturnCacheDataDontLoad policy
看起来这可能是 iOS 6 的一个错误。以下是 Robert Mao 在帖子中不得不说的内容:
A summarized work around is read the response from cache, instead of use NSURLRequestReturnCacheDataDontLoad policy:
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse != nil &&
[[cachedResponse data] length] > 0)
{
// Get cached data
....
}
关于ios - 如何在离线时使用 NSURLCache 返回缓存的 API 响应(iOS App),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15705709/