当前位置: 移动技术网 > 移动技术>移动开发>IOS > 浅谈iOS UIWebView对H5的缓存功能

浅谈iOS UIWebView对H5的缓存功能

2019年07月24日  | 移动技术网移动技术  | 我要评论

这两天在搞与h5交互的事,之前做的都是加载的静态的web页面,交互调试起来很快,这次搞的是js写的前端页面,跳转什么的都是动态的,然后就不响应了,搞了半天原来是缓存的问题,这里简单介绍一下,一般请求会使用下面的方法:

+ (instancetype)requestwithurl:(nsurl *)url;

该方法的描述如下:

creates and returns a url request for a specified url with default cache policy and timeout value.

the default cache policy is nsurlrequestuseprotocolcachepolicy and the default timeout interval is 60 seconds.

大概意思是使用的缓存策略是根据协议来的, 即 nsurlrequestuseprotocolcachepolicy. 超时时间默认是60s.也就是说类似如下的请求:

nsurlrequest *urlreq = [nsurlrequest requestwithurl:url
                      cachepolicy:nsurlrequestuseprotocolcachepolicy
                      timeoutinterval:60.f];

如果协议支持缓存的话, uiwebview 请求到的数据就是缓存数据.该缓存是需要 web 服务器支持的.看一下常用的方法

// 使用缓存数据, 如果有缓存的话
// 使用这个方法, 改变 html 或者 js 代码
// 页面不会拉取最新数据, 还是使用之前请求到的数据.
// 除非重新刷新
nsurlrequest *urlreq = [nsurlrequest requestwithurl:url
                      cachepolicy:nsurlrequestreturncachedatadontload
                    timeoutinterval:10.f];
 
// 使用协议缓存, 需要 web 服务器支持.
nsurlrequest *urlreq = [nsurlrequest requestwithurl:url
                      cachepolicy:nsurlrequestuseprotocolcachepolicy
                    timeoutinterval:60.f];
 
// 不使用缓存, 加载数据
nsurlrequest *urlreq = [nsurlrequest requestwithurl:url
                      cachepolicy:nsurlrequestreloadignoringcachedata
                    timeoutinterval:20.0];

下面是清除缓存的方法

[[nsurlcache sharedurlcache] removeallcachedresponses];
[[nsurlcache sharedurlcache] setdiskcapacity:0];
[[nsurlcache sharedurlcache] setmemorycapacity:0];

上面清除缓存的时候我们也看到了uiwebview缓存主要是利用nsurlcache来实现内存缓存或者本地缓存。内存缓存的最大值是4m(410241024),本地缓存是20m。

nsurlcache *cache = [[nsurlcache alloc] initwithmemorycapacity:4*1024 * 1024 diskcapacity:0 diskpath:nil];
[nsurlcache setsharedurlcache:cache];

其中[nsurlcache setsharedurlcache:cache]是针对当前进程中的所有clients做的共享缓存。由于ios中当前进程中只有一个app, 所以只要是当前app中uiwebview加载的h5页面,都是共享这个缓存空间的。

在加入上述功能之后,利用charles抓包,发现第一次加载h5页面时候,很多的css文件,在二次打开该页面的时候,charles没有抓到,这个也证明了,在将css等资源文件缓存之后,再次打开h5页面之后,uiwebview直接从nsurlcache中获取缓存的css等资源,不会再次发起请求。另外也可以在加载h5后,打印cache.currentmemoryusage来查看对应的内存消耗情况,如果数字大于0,就说明缓存中已经存储h5内容了。

以上是在内存中缓存h5页面,这个策略有个问题,如果用户将进程杀掉,再次打开h5的时候,需要重新缓存。还有另外一种缓存策略,在本地缓存h5内容,主要是利用在nsurlcache子类中重写下面方法。

- (nscachedurlresponse *)cachedresponseforrequest:(nsurlrequest *)request

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网