2012-03-01 91 views
0

我没有使用ASIHTTPRequest缓存功能获得缓存结果。我遵循文档的指示。当我有互联网接入时,下面的作品完美无缺。此时,我将打开飞行模式并关闭多任务应用程序。当我这样做时,我不会异步调用requestFinished。我尝试了一堆缓存策略,但似乎没有这样做。有没有人有任何想法?ASIHTTPRequest缓存不起作用

目标:能够在没有互联网连接的情况下获得缓存的JSON响应(成功从互联网加载一次后)。

- (void)viewDidLoad 
{ 
    if (!networkQueue) { 
     networkQueue = [[ASINetworkQueue alloc] init]; 
    } 
    [networkQueue reset]; 
    [networkQueue setRequestDidFinishSelector:@selector(imageFetchComplete:)]; 
    [networkQueue setRequestDidFailSelector:@selector(imageFetchFailed:)]; 
    [networkQueue setShowAccurateProgress:true]; 
    [networkQueue setDelegate:self]; 

    //Turn on default caching 
    [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]]; 

    [self loadData]; 
    [super viewDidLoad]; 
} 

-(IBAction)loadData 
{ 
    NSURL *url = [NSURL URLWithString:@"http://SOME_JSON_URL"]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    [request setDelegate:self]; 
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy]; 
    [request startAsynchronous]; 
} 

- (void)requestFinished:(ASIHTTPRequest *)request 
{ 
    if ([request didUseCachedResponse]) 
    { 
     NSLog(@"Did use cache!"); 
    } 

    NSString *responseString = [request responseString]; 
    NSLog(@"%@", responseString); 
} 
+0

@JiaYow:事实证明,如果我明确设置到期[请求setSecondsToCache:60 * 60 * 24 * 30],它作品。谢谢。 – Ryan 2012-03-01 14:27:29

回答

3

这看起来像ASIHTTPRequest认为您的数据已过期。你可以尝试重写到期设置,看看它是如何工作的:

[[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO]; 
[request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy]; 

当然,这不是最优的,因为有使用高速缓存期满很好的理由。但它可能会使你走上正轨。如果确实是到期问题,也许你可以确保服务器端的缓存设置被修改。

良好的缓存策略可以在一个文档中所述:

[request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy];