ios – AFNetworking(AFHttpClient)离线模式无法使用NSURLRequestReturnCacheDataDontLoad策略

我在我的应用程序中使用AFNetworking,并尝试通过使用缓存数据(如果可用)使其在脱机模式下工作.

我预计在我将请求缓存策略设置为NSURLRequestReturnCacheDataDontLoad后,getPath:parameters:success:failure:在离线时将使用缓存数据成功.但是,即使缓存中有数据(我通过使用代码检查缓存进行验证),getPath也会在飞行模式下失败.

AFNetworking github中有一个帖子:https://github.com/AFNetworking/AFNetworking/issues/378但似乎根本没有解决这个问题. AFNetworking的作者只是指向Apple’s document,它说:

NSURLRequestReturnCacheDataDontLoad
Specifies that the existing cache
data should be used to satisfy a request,regardless of its age or
expiration date. If there is no existing data in the cache
corresponding to a URL load request,no attempt is made to load the
data from the originating source,and the load is considered to have
Failed. This constant specifies a behavior that is similar to an
“offline” mode.

正如Apple所说,NSURLRequestReturnCacheDataDontLoad完全是为离线模式设计的.

我在iOS6中测试,我用NSURLCache和SDURLCache测试,都有相同的结果.

请求失败,错误消息:

2012-12-22 03:11:18.988 Testapp[43692:907] error: Error
Domain=NSURLErrorDomain Code=-1009 “The Internet connection appears to
be offline.” UserInfo=0x211b87c0
{NSErrorFailingURLStringKey=http://Testapp.com/api/v1/photo/latest/,
NSErrorFailingURLKey=http://Testapp.com/api/v1/photo/latest/,
NSLocalizedDescription=The Internet connection appears to be offline.,
NSUnderlyingError=0x211b9720 “The Internet connection appears to be
offline.”}

解决方法

原来,这是iOS 6中的一个错误.

AFNetworking中存在一个完全针对此问题的讨论主题https://github.com/AFNetworking/AFNetworking/issues/566

感谢guykogus关于这个问题的提示和实验.我在这个问题上度过了一个晚上!

总结的解决方法是从缓存中读取响应,而不是使用NSURLRequestReturnCacheDataDontLoad策略:

NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse != nil &&
    [[cachedResponse data] length] > 0)
{
    // Get cached data
    ....
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...