AFN的坑--NSCachedURLResponse緩存


網絡正常的情況下,如果服務器宕機或者數據庫出錯,會造成訪問服務器報錯的情況,一般報錯的內容是:無法連接到服務器或者其它錯誤。且服務器 修復后,仍然報錯。經過排查,終於找出了原因所在:AFNetworking會將Url的Response緩存,方便離線瀏覽。而且這是默認存在的,無論 是1.x還是2.x版本都存在。其方法是:

-(void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
  self.cacheResponse = block;
}

我們來看AFNetworking的方法說明:

@param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory 

or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.

問題就出在這,一旦Response被緩存后,下次不再重復發起連接,將直接將同樣地Response返回,也就是說:網絡正常的情況下,服務 器出錯,一旦服務器出錯的Response被緩存,就算服務器緊急修復后,也有可能造成iOS客戶端持續報錯。這種情況將是致命的。

來看蘋果是怎么說的:

1、An NSCachedURLResponse object encapsulates an NSURLResponse object, an NSData object containing the content corresponding to the response, and an NSDictionary containing application specific information.

The NSURLCache system stores and retrieves instances of NSCachedURLResponse.

這句話簡單介紹了一下NSCachedURLResponse的構成,以及被NSURLCache來存儲和讀取。最重要的在下面:

2、我們來看下系統提供的URLCache緩存策略:

NSURLCacheStoragePolicy

These constants specify the caching strategy used by an NSCachedURLResponse object.
typedef enum
{
NSURLCacheStorageAllowed,

NSURLCacheStorageAllowedInMemoryOnly,

NSURLCacheStorageNotAllowed,

} NSURLCacheStoragePolicy;

 

我們依次來解讀:

NSURLCacheStorageAllowed:
Specifies that storage in NSURLCache is allowed without restriction.

沒有特殊指定時采取該策略。

Important: iOS prior to version 5 ignores this cache policy, and instead treats it as NSURLCacheStorageAllowedInMemoryOnly.

 

重要:iOS在5之前都是忽略這個協議的,代替的是NSURLCacheStorageAllowedInMemoryOnly。(也就是說,6之后這個協議是默認協議,既可以緩存在內存,也可以緩存在磁盤。如果是內存,我們重啟設備就可以解決,如果是磁盤,必須硬代碼去解決)

NSURLCacheStorageAllowedInMemoryOnly:

Specifies that storage in NSURLCache is allowed; however storage should be restricted to memory only.

這個不用過多解釋,緩存在內存。

 

NSURLCacheStorageNotAllowed

Specifies that storage in NSURLCache is not allowed in any fashion, either in memory or on disk.

不允許任何協議的緩存,即不允許緩存。

解決方案:

幸運的是,AFNetworking利用的系統自有類存儲,我們可以修改其源代碼:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

這一句代碼是清除所有的URL緩存Response。這樣一來,就可以解決這一問題所在。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM