ASIHTTPRequest缓存策略的设置

来源:互联网 发布:华讯网络怎么样 编辑:程序博客网 时间:2024/04/27 14:53

ASIHTTPRequest 是一款强大的网络请求框架,该框架自带了数据的缓存策略,下面来介绍该功能的使用方法。

 

1.创建缓存对象

Java代码 
  1. //创建缓存对象  
  2. ASIDownloadCache *asiCache = [[ASIDownloadCache alloc] init];  
  3. //设置缓存目录,这里设置沙盒目录下的Documents目录作为缓存目录  
  4. NSString *document = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];  
  5. [asiCache setStoragePath:document];  
  6. //设置缓存策略  
  7. [asiCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];  
 

2.请求对象设置缓存

Java代码 
  1. //创建数据请求对象  
  2. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlstring]];  
  3. /* 
  4.  *设置缓存策略 
  5.  *ASICacheForSessionDurationCacheStoragePolicy 程序下次启动会清除本地的缓存数据 
  6.  *ASICachePermanentlyCacheStoragePolicy 是持久缓存,程序下次启动,缓存仍然还在 
  7.  */  
  8. request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;  
  9. [request setDownloadCache:[UserContext shareInstance].cache];  
  10. //开始异步请求网络  
  11. [request startAsynchronous];  
 

 

3.数据请求完成后

Java代码 
  1. //网络数据加载完成后调用的block  
  2. [request setCompletionBlock:^{  
  3.     NSString *responseString = request.responseString;  
  4.     //打印返回的数据  
  5.     NSLog(@"%@",responseString);  
  6.       
  7.    //判断返回的数据是否来自本地缓存  
  8.     if (request.didUseCachedResponse) {  
  9.         NSLog(@"使用缓存数据");  
  10.     } else {  
  11.         NSLog(@"请求网络数据");  
  12.     }  
  13.       
  14. }];  
 

原创粉丝点击