我想利用NSURLCache返回我在iOS应用程序中进行API调用的缓存响应.当设备联机时,如果足够近,我想返回缓存的响应,否则从远程获取.当设备脱机时,我想立即返回缓存的响应(如果有的话),而不管它的年龄.
我正在使用AFNetworking.我所做的API调用是对我控制的服务器.协议是HTTPS. Cache-Control响应头目前是“max-age = 0,public”.我目前没有设置缓存相关的请求标头(应该?).在脱机时,将请求的缓存策略设置为NSURLRequestReturnCacheDataDontLoad,并在线时使用默认的NSURLRequestUseProtocolCachePolicy.并且我可以在磁盘上的默认Cache.db中看到请求及其响应.但是当我离线时,所有请求都失败(没有缓存的响应(尽管看起来已被缓存))被使用/返回.
每http://nshipster.com/nsurlcache/我在didFinishLaunchingWithOptions中初始化sharedURLCache,并将AFNetworking setCacheResponse块设置为如下所示:
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 .... }