紧接这一篇:
在开始进行缓存之前,我们首先创建一个数据持久化的东东,这里使用的是:
abcd.xcdatamodeld
创建完之后我们会生成一个h和m文件:
@interface CachedURLResponse :NSManagedObject
@property (nonatomic,retain)NSDate * timestamp;
@property (nonatomic,retain)NSData * data;
@property (nonatomic,retain)NSString * encoding;
@property (nonatomic,retain)NSString * mimeType;
@property (nonatomic,retain)NSString * url;
@end
上面的内容分别存储网页的 时间戳 数据 编码方式 超文本类型 以及 url。利用这些参数我们就可以还原网页。通过前面的分析我们直到,NSURLProtocol中startLoading用于从网页上抓去数据:
下面分别修改三个方法实现一个简单的缓存功能:
/**
@method: 获取网站上的数据 建立connect连接
@parma :
@return:
*/
- (void)startLoading {
// 1.检查是否使用本地缓存
CachedURLResponse *cachedResponse = [selfcachedResponseForCurrentRequest];
if (cachedResponse) {
NSLog(@"serving response from cache");
// 2.
NSData *data = cachedResponse.data;
NSString *mimeType = cachedResponse.mimeType;
NSString *encoding = cachedResponse.encoding;
// 3.
NSURLResponse *response = [[NSURLResponsealloc]initWithURL:self.request.URL
MIMEType:mimeType
expectedContentLength:data.length
textEncodingName:encoding];
// 4.
[self.clientURLProtocol:selfdidReceiveResponse:responsecacheStoragePolicy:NSURLCacheStorageNotAllowed];
[self.clientURLProtocol:selfdidLoadData:data];
[self.clientURLProtocolDidFinishLoading:self];
}else {
// 5.
NSLog(@"serving response from NSURLConnection");
NSMutableURLRequest *newRequest = [self.requestmutableCopy];
[NSURLProtocolsetProperty:@YESforKey:@"MyURLProtocolHandledKey"inRequest:newRequest];
self.connection = [NSURLConnectionconnectionWithRequest:newRequestdelegate:self];
}
}
#pragma mark --NSURLProtocol Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.clientURLProtocol:selfdidReceiveResponse:responsecacheStoragePolicy:NSURLCacheStorageNotAllowed];
self.response = response;
self.mutableData = [[NSMutableDataalloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.clientURLProtocol:selfdidLoadData:data];
[self.mutableDataappendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.clientURLProtocolDidFinishLoading:self];
[selfsaveCachedResponse];
}
断开网络,运行之后会看到和IOS网络篇1之截取本地URL请求(NSURLProtocol)相同的效果,不过这个界面可是从本地缓存中加载的。