陈斌彬的技术博客

Stay foolish,stay hungry

UIWebview 的缓存策略和验证,以及 Web 相关

缓存策略 NSURLRequestCachePolicy

NSURLRequestUseProtocolCachePolicy 缓存策略定义在 web 协议实现中,用于请求特定的URL。是默认的URL缓存策略 Specifies that the caching logic defined in the protocol implementation, if any, is used for a particular URL load request. This is the default policy for URL load requests.

NSURLRequestReloadIgnoringLocalCacheData 从服务端获取数据,忽略本地缓存

Specifies that the data for the URL load should be loaded from the originating source. No existing cache data should be used to satisfy a URL load request.

NSURLRequestReloadIgnoringLocalAndRemoteCacheData

不仅忽略本地的缓存数据,还忽略中间网络媒介(如代理服务器)忽略缓存。直接从最原始的服务器拿取 Specifies that not only should the local cache data be ignored, but that proxies and other intermediates should be instructed to disregard their caches so far as the protocol allows.

NSURLRequestReloadIgnoringCacheData 被NSURLRequestReloadIgnoringLocalCacheData替换了

Replaced by NSURLRequestReloadIgnoringLocalCacheData.

NSURLRequestReturnCacheDataElseLoad

已经存在的缓存数据用于请求返回,不管它的过期日期和已经存在了多久。如果没有请求对应的缓存数据,从数据源读取 Specifies that the existing cached data should be used to satisfy the request, regardless of its age or expiration date. If there is no existing data in the cache corresponding the request, the data is loaded from the originating source.

NSURLRequestReturnCacheDataDontLoad

已经存在的缓存数据用于请求返回,不管它的过期日期和已经存在了多久。如果没有请求对应的缓存数据,不要去数据源读取,该请求被设置为失败,这种情况多用于离线模式

Specifies that the existing cache data should be used to satisfy a request, regardless of its age or expiration date. If there is no existing data in the cache corresponding to a URL load request, no attempt is made to load the data from the originating source, and the load is considered to have failed. This constant specifies a behavior that is similar to an “offline” mode.

NSURLRequestReloadRevalidatingCacheData

已经存在的缓存数据先去数据源验证有效性,如果无效,将从数据源获取 Specifies that the existing cache data may be used provided the origin source confirms its validity, otherwise the URL is loaded from the origin source.

NSURLRequestUseProtocolCachePolicy 和 NSURLRequestReloadRevalidatingCacheData 区别

个人意见,仅供参考,如有错误,请指出来,这对我很重要,谢谢

NSURLRequestReloadRevalidatingCacheData 是一定要和原始的数据源验证 cache 是否有效。 而NSURLRequestUseProtocolCachePolicy 是根据 web 的协议来控制缓存,服务端返回数据的 head 有相关的信息。它可能会返回中间网络媒介(如代理服务器中的数据)

针对缓存策略做一下本地测试,这是非常有必要的

NSURL *webUrl = [NSURL URLWithString:@"http://localhost/test.txt"];       
NSURLRequest *request =[NSURLRequest requestWithURL:webUrl cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];       
[self.mainWebView loadRequest:request];  

这里使用NSURLRequestReloadRevalidatingCacheData, 返回cache数据一定要先验证数据有效。

Resource Reference