我爲我的所有網絡操作使用AFNetworking
和SDURLCache
。帶AFNetworking和脫機模式不起作用的SDURLCache
我SDURLCache
一套這樣的:
SDURLCache *urlCache = [[SDURLCache alloc]
initWithMemoryCapacity:1024*1024*2 // 2MB mem cache
diskCapacity:1024*1024*15 // 15MB disk cache
diskPath:[SDURLCache defaultCachePath]];
[urlCache setMinCacheInterval:1];
[NSURLCache setSharedURLCache:urlCache];
我所有的請求都使用的CachePolicy NSURLRequestUseProtocolCachePolicy
,根據蘋果的文檔,其工作原理是這樣的:
如果NSCachedURLResponse沒有爲請求存在,那麼 數據從原始源獲取。如果該請求有緩存的 響應,則URL加載系統檢查響應 以確定它是否指定內容必須重新驗證。如果 的內容必須重新驗證,則連接到 原始源,以查看它是否已更改。如果它沒有改變,則 然後從本地緩存返回響應。如果它發生了變化,則從原始源獲取數據 。
如果緩存的響應未指定內容必須重新生效,則會檢查響應 中指定的最大使用期限或到期日期。如果緩存的響應足夠近,則從本地緩存中返回 響應。如果響應是 確定爲陳舊,則檢查始發源以獲取更新的 數據。如果更新的數據可用,則將從 原始源獲取數據,否則將從緩存中返回。
因此,即使在飛行模式下,只要緩存沒有陳舊,一切都可以完美運行。當緩存過期時(max-age和其他),失敗塊被調用。
我已經挖了一點SDURLCache
內,此方法返回的有效數據的響應(我已經分析的數據爲字符串,它包含緩存信息)
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
request = [SDURLCache canonicalRequestForRequest:request];
NSCachedURLResponse *memoryResponse =
[super cachedResponseForRequest:request];
if (memoryResponse) {
return memoryResponse;
}
NSString *cacheKey = [SDURLCache cacheKeyForURL:request.URL];
// NOTE: We don't handle expiration here as even staled cache data is
// necessary for NSURLConnection to handle cache revalidation.
// Staled cache data is also needed for cachePolicies which force the
// use of the cache.
__block NSCachedURLResponse *response = nil;
dispatch_sync(get_disk_cache_queue(), ^{
NSMutableDictionary *accesses = [self.diskCacheInfo
objectForKey:kAFURLCacheInfoAccessesKey];
// OPTI: Check for cache-hit in in-memory dictionary before to hit FS
if ([accesses objectForKey:cacheKey]) {
response = [NSKeyedUnarchiver unarchiveObjectWithFile:
[_diskCachePath stringByAppendingPathComponent:cacheKey]];
if (response) {
// OPTI: Log entry last access time for LRU cache eviction
// algorithm but don't save the dictionary
// on disk now in order to save IO and time
[accesses setObject:[NSDate date] forKey:cacheKey];
_diskCacheInfoDirty = YES;
}
}
});
// OPTI: Store the response to memory cache for potential future requests
if (response) {
[super storeCachedResponse:response forRequest:request];
}
return response;
}
所以在這點我不知道做什麼,因爲我相信,響應由操作系統來處理,然後AFNetworking
收到
- (void)connection:(NSURLConnection *)__unused connection
didFailWithError:(NSError *)error
內AFURLConnectionOperation
。
我現在面對完全相同的問題。你找到了解決方案嗎? – mkto 2012-05-20 18:33:43
沒有,我做了一個awefull解決辦法,沒什麼可:-( – Ecarrion 2012-05-21 15:46:01
我已經發出了郵件的作者皮特誰分叉的SDURLCache驕傲希望他有一個答案.. – mkto 2012-05-22 01:46:56