先说一下有缓存的情况下:
- if (model.data && model.MIMEType) {
- NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:model.MIMEType expectedContentLength:model.data.length textEncodingName:nil];
- [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
- [self.client URLProtocol:self didLoadData:model.data];
- [self.client URLProtocolDidFinishLoading:self];
- return;
- }
(model是缓存数据)有缓存的情况下,直接应用缓存的数据和MIME类型,然后构建NSURLResponse,然后经由过程协定client调用代劳办法。这里的client是一个protocol,如下:
该协定供给了NSURLProtocol子类与URL Loading System进行沟通的接口。一个APP必定不要去实现这个协定。有缓存的情况下调用回调办法,然落后行处理。
在没有缓存的情况下:
实例化一个connection,然后提议请求。在我们收到response的时刻:
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
- self.responseData = [[NSMutableData alloc] init];
- self.responseMIMEType = response.MIMEType;
- [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
- }
紧接着就是吸法术据:
接收完数据之后便调用了:
- @protocol NSURLProtocolClient <NSObject>
- - (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse;
- - (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse;
- - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy;
- - (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data;
- - (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol;
- - (void)URLProtocol:(NSURLProtocol *)protocol didFailWithError:(NSError *)error;
- - (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
- - (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
- @end
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
- ZGCacheModel *model = [ZGCacheModel new];
- model.data = self.responseData;
- model.MIMEType = self.responseMIMEType;
- [self setMiType:model.MIMEType withKey:[self.request.URL path]];//userdefault存储MIMEtype
- [[ZGUIWebViewCache sharedWebViewCache] setCacheWithKey:self.request.URL.absoluteString value:model];
推荐阅读
CTO练习营 | 12月3-5日,深圳,是时刻成为优良的技巧治理者了在印度,大年夜量始创企业欲望将AI技巧应用于相干范畴以知足13.24亿人口的需求。这是一项巨大年夜的事业,对于美国和全球其他地区的医疗保健>>>详细阅读
本文标题:我是如何一步一步实现网页离线缓存的?
地址:http://www.17bianji.com/lsqh/39272.html
1/2 1