NSURLCache缓存响应问题 [英] NSURLCache Problem with cache response
问题描述
我正在编写一个iPhone应用程序,其中一个标签是twitter提要,我正在解析twitter xml并将其很好地放在表格视图中。
如果没有互联网连接,我想显示上次我们有互联网连接的缓存结果,并且表格已更新。
我正在使用NSURLCache:
I'm writing an iPhone application, one of it's tabs is a twitter feed, i'm parsing twitter xml and putting it nicely inside a table view. In case there is no internet connection I would like to show cache results of the last time we had internet connection and the tables were updated. I'm using NSURLCache for that like so:
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:xmlLink]
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
NSURLCache *sharedCache = [NSURLCache sharedURLCache];
NSCachedURLResponse *response = [sharedCache cachedResponseForRequest:theRequest];
if (response) {
NSLog(@"Got Response");
} else {
NSLog(@"Didn't got Response");
}
self.objectFeedConnection = [[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES] autorelease];
我可以看到NSLog第一次输出没有得到回复,因为它是第一次访问本网站的时间( http://www.twitter.com/ .. 。)
我还可以看到响应被缓存,因为我实现了在initWithRequest启动后调用的willCacheResponse方法,如下所示:
I can see that for the first time NSLog outputs "Didn't got response" since it's the first time visiting this website (http://www.twitter.com/...) I can also see that the response is being cached, since i implemented the willCacheResponse method which is being called after the initWithRequest was launched, like so:
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
NSLog(@"willCache Reponse");
NSCachedURLResponse *newCachedResponse = nil;
if ([[[[cachedResponse response] URL] scheme] isEqual:@"http"]) {
newCachedResponse = [[[NSCachedURLResponse alloc]
initWithResponse:[cachedResponse response]
data:[cachedResponse data]
userInfo:nil
storagePolicy:[cachedResponse storagePolicy]]
autorelease];
}
return newCachedResponse;
}
我第二次访问这个网站时,我可以清楚地看到NSLog输出Got响应这意味着有一个缓存命中,因此willCacheResponse应该不再次被调用,但由于一些奇怪的原因它被一次又一次地调用,并没有将信息从缓存中拉出来,而是尝试再次缓存它。
The second time i visit this site i can clearly see that NSLog outputs "Got Response" which means that there was a cache hit, hence willCacheResponse should not be called again, but for some strange reason it is called again and again and does not pull the information out of the cache, instead it try to cache it again.
知道造成这个问题的原因是什么吗?
Any idea what causing this issue ?
谢谢!
推荐答案
请尝试使用此库: https: //github.com/rs/SDURLCache
这篇关于NSURLCache缓存响应问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!