之前做項(xiàng)目遇到這么一個問題:網(wǎng)絡(luò)正常的情況下灿巧,如果服務(wù)器宕機(jī)或者數(shù)據(jù)庫出錯,會造成訪問服務(wù)器報(bào)錯的情況揽涮,一般報(bào)錯的內(nèi)容是:無法連接到服務(wù)器或者其它錯誤抠藕。且服務(wù)器修復(fù)后,仍然報(bào)錯绞吁。經(jīng)過排查幢痘,終于找出了原因所在:AFNetworking會將Url的Response緩存,方便離線瀏覽家破。而且這是默認(rèn) 存在的
- (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被緩存后汰聋,下次不再重復(fù)發(fā)起連接门粪,將直接將同樣地Response返回,也就是說:網(wǎng)絡(luò)正常的情況下烹困,服務(wù)器出錯玄妈, 一旦服務(wù)器出錯的Response被緩存,就算服務(wù)器緊急修復(fù)后髓梅,也有可能造成移動客戶端持續(xù)報(bào)錯拟蜻。這種情況很難發(fā)現(xiàn)。
我們再來看蘋果是
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的構(gòu)成酝锅,以及被NSURLCache來存儲和讀取。最重要的在下面:
2奢方、我們來看下系統(tǒng)提供的URLCache緩存策略:
NSURLCacheStoragePolicyThese 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.
NSURLCacheStorageAllowedInMemoryOnly:
Specifies that storage in NSURLCache is allowed; however storage should be restricted to memory only.
這個不用過多解釋搔扁,緩存在內(nèi)存:
NSURLCacheStorageNotAllowed
Specifies that storage in NSURLCache is not allowed in any fashion, either in memory or on disk.
不允許任何協(xié)議的緩存,即不允許緩存蟋字。
解決方案:
幸運(yùn)的是稿蹲,AFNetworking利用的系統(tǒng)自有類存儲,我們可以修改其源代碼:
[[NSURLCache sharedURLCache] removeAllCachedResponses];
這一句代碼是清除所有的URL緩存Response鹊奖。這樣一來苛聘,就可以解決這一問題所在。
PS:我覺得可以根據(jù)業(yè)務(wù)修改代碼邏輯,做到報(bào)錯的響應(yīng)不緩存设哗,這樣才比較合理璧尸。單純清空全部緩存或者不啟用緩存的話就失去緩存的意義了。
ref:http://blog.csdn.net/wojiaoliuli521/article/details/19831077