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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/iOS/334081.html

猜你在找的iOS相关文章