ios url缓存策略——NSURLCache、 NSURLRequest、Http规则

来源:互联网 发布:java并发编程 豆瓣 编辑:程序博客网 时间:2024/05/16 13:57
缓存种类:
1.全量缓存。
利用服务端返回的Last-Modified和Etags,客户端发送If-Modified-Since或If-None-Match,让服务端做逻辑处理返回200(正常)、304(无改变,ResponseDate = nil)、404(失败)。这样有缓存时就不再需要网页内容的那部分流量。
2.只做资源缓存。
利用NSURLRequestReloadRevalidatingCacheData(实际上就是NSURLRequestReloadIgnoringLocalCacheData加上一个比对过程)做校验,如果有新的,再去加载新页面和图片。反之利用缓存即可。

其实还有另外一种方式,每次都NSURLRequestReloadIgnoringLocalCacheData做重新加载网页,根据加载下来的Response头中的Last-Modified和缓存中的时间对比判断,如果旧的,就用缓存,如果是新的,就用在线的。






一:url 缓存策略

 

NSURLRequest

 

 

requestWithURL:cachePolicy:timeoutInterval:

 

1:NSURLRequestUseProtocolCachePolicy


This flag will use the underlying protocol’s caching mechanism if the protocol
supports it.

 

基础策略

 

2:NSURLRequestReloadIgnoringLocalCacheData


This flag specifies that the local cached copy of the resource that is about to be
downloaded must be disregarded and the remote cache policy must be effective.
If there is a local copy of the resource, managed by the framework itself, it will be
ignored.

 

忽略本地缓存

 

 

3:NSURLRequestReturnCacheDataElseLoad

 


This flag specifies that the cached data must be used before attempting to load the
data from the original source. The cached data could be protocol-based cached or
locally cached. If there is no cached data, the data will be downloaded from the
original source.

 

首先使用缓存,如果没有本地缓存,才从原地址下载

 

 

4:NSURLRequestReturnCacheDataDontLoad


This flag specifies that only the local cached data must be used. If the data has not
been cached, the request will fail. This is a great flag to use whenever your application
wants to perform operations in offline mode (such as the Offline Mode in
web browsers).

 

使用本地缓存,从不下载,如果本地没有缓存,则请求失败。此策略多用于离线操作

 

5:NSURLRequestReloadIgnoringLocalAndRemoteCacheData


This flag disregards any type of caching involved in the process, local and remote,
and always attempts to download the data from the original source.

 

无视任何的缓存策略,无论是本地的还是远程的,总是从原地址重新下载

 

 

6:NSURLRequestReloadRevalidatingCacheData

 


This flag specifies that the original source of data must validate the local cache (if
any) before an attempt is made to download the data from the original source. If
there is a copy of the original source cached locally and the remote source specifies
that the cached data is valid, the data won’t be downloaded again. In any other
case, the data will be downloaded from the original source.

 

如果本地缓存是有效的则不下载。其他任何情况都从原地址重新下载

 

 

二:NSURLCache

 

NSURLCache *urlCache = [NSURLCache sharedURLCache];

 

 

In iOS, NSURLCache supports caching data only in memory and not
on disk.

 

(NSURLCache 仅支持内存缓存,不支持硬盘缓存)

 

 

 

C代码  收藏代码
  1. (voiddownloadURL:(NSString *)paramURLAsString{  
  2.   
  3. if ([paramURLAsString length] == 0){  
  4.     NSLog(@"Nil or empty URL is given");  
  5.     return 
  6.  
  7.   
  8.   
  9. NSURLCache *urlCache [NSURLCache sharedURLCache];  
  10.   
  11.   
  12. [urlCache setMemoryCapacity:1*1024*1024];  
  13.   
  14.   
  15. NSURL *url [NSURL URLWithString:paramURLAsString];  
  16.   
  17.   
  18. NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];  
  19.   
  20.   
  21. NSCachedURLResponse *response =[urlCache cachedResponseForRequest:request];  
  22.   
  23.   
  24. if (response != nil){  
  25.     NSLog(@"Cached response exists. Loading data from cache...");  
  26.     [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];  
  27.  
  28.   
  29. self.connection nil;  
  30.   
  31.   
  32. NSURLConnection *newConnection [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];  
  33. self.connection newConnection;  
  34. [newConnection release];  
  35.   
  36. }


-------------------------------------------------------------------------------------------------

http响应Last-Modified和ETag

在http中Last-Modified 与If-Modified-Since 都是用于记录页面最后修改时间的 HTTP 头信息,注意,在这 Last-Modified 是由服务器往客户端发送的 HTTP 头,另一个 If-Modified-Since是由客户端往服务器发送的头,可以看到,再次请求本地存在的 cache 页面时,客户端会通过 If-Modified-Since 头将先前服务器端发过来的 Last-Modified 最后修改时间戳发送回去,这是为了让服务器端进行验证,通过这个时间戳判断客户端的页面是否是最新的,如果不是最新的,则返回新的内容,如果是最新的,则 返回 304 告诉客户端其本地 cache 的页面是最新的,于是客户端就可以直接从本地加载页面了,这样在网络上传输的数据就会大大减少,同时也减轻了服务器的负担。而且在一些ajax应用中,要 求获取的数据永远是最新的,而不是读取位于缓存中的数据,做这样的设置是非常有必要的。

基础知识
  1) 什么是”Last-Modified”?
  在浏览器第一次请求某一个URL时,服务器端的返回状态会是200,内容是你请求的资源,同时有一个Last-Modified的属性标记此文件在服务期端最后被修改的时间,格式类似这样:
  Last-Modified: Fri, 12 May 2006 18:53:33 GMT
  客户端第二次请求此URL时,根据 HTTP 协议的规定,浏览器会向服务器传送 If-Modified-Since 报头,询问该时间之后文件是否有被修改过:
  If-Modified-Since: Fri, 12 May 2006 18:53:33 GMT
   如果服务器端的资源没有变化,则自动返回 HTTP 304 (Not Changed.)状态码,内容为空,这样就节省了传输数据量。当服务器端代码发生改变或者重启服务器时,则重新发出资源,返回和第一次请求时类似。从而 保证不向客户端重复发出资源,也保证当服务器有变化时,客户端能够得到最新的资源。
  2) 什么是”Etag”?
   HTTP 协议规格说明定义ETag为“被请求变量的实体值” (参见 —— 章节 14.19)。 另一种说法是,ETag是一个可以与Web资源关联的记号(token)。典型的Web资源可以一个Web页,但也可能是JSON或XML文档。服务器单 独负责判断记号是什么及其含义,并在HTTP响应头中将其传送到客户端,以下是服务器端返回的格式:
  ETag: "50b1c1d4f775c61:df3"
  客户端的查询更新格式是这样的:
  If-None-Match: W/"50b1c1d4f775c61:df3"
  如果ETag没改变,则返回状态304然后不返回,这也和Last-Modified一样。本人测试Etag主要在断点下载时比较有用。
  Last-Modified和Etags如何帮助提高性能?
   聪明的开发者会把Last-Modified 和ETags请求的http报头一起使用,这样可利用客户端(例如浏览器)的缓存。因为服务器首先产生 Last-Modified/Etag标记,服务器可在稍后使用它来判断页面是否已经被修改。本质上,客户端通过将该记号传回服务器要求服务器验证其(客 户端)缓存。
  过程如下:

  1. 客户端请求一个页面(A)。
  2. 服务器返回页面A,并在给A加上一个Last-Modified/ETag。
  3. 客户端展现该页面,并将页面连同Last-Modified/ETag一起缓存。
  4. 客户再次请求页面A,并将上次请求时服务器返回的Last-Modified/ETag一起传递给服务器。
  5. 服务器检查该Last-Modified或ETag,并判断出该页面自上次客户端请求之后还未被修改,直接返回响应304和一个空的响应体。
原创粉丝点击