NSURLCache理解

47 篇文章 0 订阅
34 篇文章 0 订阅

iOS网络请求中缓存技术用到了NSURLCache类,默认支持支持内存缓存和硬盘缓存。NSURLCache对NSURLRequest及其对应的NSCachedURLResponse缓存,并存放到本地数据库中。(就是说只要你使用NSURLRequest做网络请求,系统默认使用NSURLCache帮你做缓存)

NSURLCache的常见方法

1)获得全局缓存对象(没必要手动创建)NSURLCache*cache = [NSURLCache sharedURLCache];

2)设置内存缓存的最大容量(字节为单位,默认为512KB)- (void)setMemoryCapacity:(NSUInteger)memoryCapacity;

3)设置硬盘缓存的最大容量(字节为单位,默认为10M)- (void)setDiskCapacity:(NSUInteger)diskCapacity;

4)硬盘缓存的位置:沙盒/Library/Caches

5)取得某个请求的缓存-(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;

6)清除某个请求的缓存-(void)removeCachedResponseForRequest:(NSURLRequest *)request;

7)清除所有的缓存-(void)removeAllCachedResponses;

代码演示:

-(IBAction)post:(id)sender{

   NSURLCache *cache = [NSURLCache sharedURLCache];

   // 1.创建请求

   NSURL *url = [NSURLURLWithString:@"http://api1.zhimamei.com/appProductSearch"];

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];


   NSCachedURLResponse *response = [cachecachedResponseForRequest:request];

   if (response) {

       

       NSLog(@"这个请求已经存在缓存");

       NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response.response;

        NSString *string =[httpResponse.allHeaderFields objectForKey:@"Date"];

       NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];

       [inputFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_CN"]];

       [inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];

       NSDate* inputDate = [inputFormatter dateFromString:string];

       

       NSDate *now = [NSDate date];

        //判断缓存是否过期:超过两小时

       if ([now timeIntervalSinceDate:inputDate] > 2 * 60 * 60  ) {

           

           NSURLCache *cache = [NSURLCache sharedURLCache];

           [cache removeCachedResponseForRequest:request];

           

           //设置缓存策略:忽略缓存,重新请求

           request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

           

       }else{

           

           //设置缓存策略:有缓存就用缓存,没有缓存就不发请求,当做请求出错处理(用于离线模式)

           request.cachePolicy = NSURLRequestReturnCacheDataDontLoad;

       }

       

    }else {

       

       NSLog(@"这个请求没有缓存");

       

    }

   

   //发送请求

   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError*connectionError) {

       if (data) {

           NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableLeaves error:nil];

           

           NSLog(@"%@", dict);

           

       }

   }];

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值