微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
    ....
}

原文地址:https://www.jb51.cc/iOS/334081.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐