作家
登录

我是如何一步一步实现网页离线缓存的?

作者: 来源: 2017-11-29 12:04:29 阅读 我要评论

先说一下有缓存的情况下:

  1. if (model.data && model.MIMEType) { 
  2.         NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:model.MIMEType expectedContentLength:model.data.length textEncodingName:nil]; 
  3.         [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; 
  4.         [self.client URLProtocol:self didLoadData:model.data]; 
  5.         [self.client URLProtocolDidFinishLoading:self]; 
  6.         return
  7.     } 

(model是缓存数据)有缓存的情况下,直接应用缓存的数据和MIME类型,然后构建NSURLResponse,然后经由过程协定client调用代劳办法。这里的client是一个protocol,如下:

该协定供给了NSURLProtocol子类与URL Loading System进行沟通的接口。一个APP必定不要去实现这个协定。有缓存的情况下调用回调办法,然落后行处理。

在没有缓存的情况下:

实例化一个connection,然后提议请求。在我们收到response的时刻:

  1. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
  2.     self.responseData = [[NSMutableData alloc] init]; 
  3.     self.responseMIMEType = response.MIMEType; 
  4.     [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; 

紧接着就是吸法术据:

接收完数据之后便调用了:

  1. @protocol NSURLProtocolClient <NSObject>  
  2. - (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse; 
  3. - (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse;  
  4. - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy; 
  5. - (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data;  
  6. - (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol;  
  7. - (void)URLProtocol:(NSURLProtocol *)protocol didFailWithError:(NSError *)error;  
  8. - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;  
  9. - (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;  
  10. @end 
  1. - (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
  2.     ZGCacheModel *model = [ZGCacheModel new]; 
  3.     model.data = self.responseData; 
  4.     model.MIMEType = self.responseMIMEType; 
  5.     [self setMiType:model.MIMEType withKey:[self.request.URL path]];//userdefault存储MIMEtype 
  6.      
  7.      
  8.     [[ZGUIWebViewCache sharedWebViewCache] setCacheWithKey:self.request.URL.absoluteString value:model]; 

      推荐阅读

      医生供不应求怎么办?印度创企利用 AI 重塑医疗保健系统

    CTO练习营 | 12月3-5日,深圳,是时刻成为优良的技巧治理者了在印度,大年夜量始创企业欲望将AI技巧应用于相干范畴以知足13.24亿人口的需求。这是一项巨大年夜的事业,对于美国和全球其他地区的医疗保健>>>详细阅读


    本文标题:我是如何一步一步实现网页离线缓存的?

    地址:http://www.17bianji.com/lsqh/39272.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)