对于每个NSURLRequest来讲都对应着一个响应的 NSURLRequestCachePolicy 缓存策略,缓存策略分别为:

typedef NS_ENUM(NSUInteger, NSURLRequestCachePolicy)
{
    NSURLRequestUseProtocolCachePolicy = 0,

    NSURLRequestReloadIgnoringLocalCacheData = 1,
    NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented
    NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,

    NSURLRequestReturnCacheDataElseLoad = 2,
    NSURLRequestReturnCacheDataDontLoad = 3,

    NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented
};

默认情况下AFN的缓存策略采用 NSURLRequestUseProtocolCachePolicy,即如果一个NSCachedURLResponse对于请求并不存在,数据将会从源端获取。如果请求拥有一个缓存的响应,那么URL加载系统会检查这个响应来决定,如果它指定内容必须重新生效的话。假如内容必须重新生效,将建立一个连向源端的连接来查看内容是否发生变化。假如内容没有变化,那么响应就从本地缓存返回数据。如果内容变化了,那么数据将从源端获取。

在请求以及响应都正常的情况下,不会发生问题,当请求报错的时候AFN对于同一个URL敬请访问的时候,会直接取之前缓存的响应结果,结果就是当服务器数据正常的情况下也会返回之前报错的时候的响应,这显然会造成问题!
AFN本身是通过系统的NSURLCache来做缓存的,所以为了解决问题,就是在网络请求发生错误的时候调用即可,
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:@"xxxx"];

  1. Hello there,

    My name is Aly and I would like to know if you would have any interest to have your website here at luckyncl.top promoted as a resource on our blog alychidesign.com ?

    We are in the midst of updating our broken link resources to include current and up to date resources for our readers. Our resource links are manually approved allowing us to mark a link as a do-follow link as well
    .
    If you may be interested please in being included as a resource on our blog, please let me know.

    Thanks,
    Aly

Leave a Reply

电子邮件地址不会被公开。

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>