本文介绍了AFNetworking(AFHttpClient)离线模式无法使用NSURLRequestReturnCacheDataDontLoad策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using AFNetworking in my app and try to make it work in the offline mode by use the cached data if available.

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

I expected after I set the request cache policy to NSURLRequestReturnCacheDataDontLoad, getPath:parameters:success:failure: will success with the cached data while offline. However, even if there are data in the cache (I verified by check the cache with the code), getPath will simply fail in airplane mode.

AFNetworking github中有一个帖子:但似乎根本没有解决这个问题。 AFNetworking的作者只是指向,它说:

There was a thread in AFNetworking github: https://github.com/AFNetworking/AFNetworking/issues/378 But seemed the issue is not addressed at all. The author of AFNetworking simply point to Apple's document, and it said:

正如Apple所说,NSURLRequestReturnCacheDataDontLoad是精确设计的用于离线模式。

As Apple said, NSURLRequestReturnCacheDataDontLoad is exactly designed for offline mode.

我在iOS6中测试,我使用NSURLCache和SDURLCache进行测试,结果都相同。

I am testing in iOS6, I tested with both NSURLCache and SDURLCache, all have the same result.

请求失败,错误消息:


推荐答案

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

Turned out, it's a bug in iOS 6.

有一个讨论主题在AFNetworking中完全针对这个问题:

There is a discussion thread in AFNetworking exactly for this problem: https://github.com/AFNetworking/AFNetworking/issues/566

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

Thanks for guykogus' tips and experiments on this issue. I spent a night on this issue!

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

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

这篇关于AFNetworking(AFHttpClient)离线模式无法使用NSURLRequestReturnCacheDataDontLoad策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 23:17