如果你的App是通过UIWebView来展示html格式的内容,里面的图片加载由UIWebView自动进行,如果你想在wifi环境下离线下载网页中的图片该怎么办?
这里我们介绍一种比较简单的方法,利用NSURLCache来实现。
@interface MyURlCache : NSURLCache
@end
@implementation MyURlCache
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request{
//判断URL
if ([request.URL.host isEqualToString:kMyHost]){
//读取本地缓存数据
NSData * data = [self getDataOfUrlString:request.URL.absoluteString];
if(data){
//直接生成NSCachedURLResponse返回
NSURLResponse * response = [[NSURLResponse alloc] initWithURL:request.URL MIMEType:@"image/jpg" expectedContentLength:data.length textEncodingName:nil];
return [[NSCachedURLResponse alloc] initWithResponse:response data:data];
}
}
//没有本地缓存,按默认方式处理
return [super cachedResponseForRequest:request];
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request{
if ([request.URL.host isEqualToString:kMyHost]&& [cachedResponse.response isKindOfClass:[NSHTTPURLResponse class]] && [(NSHTTPURLResponse*)cachedResponse.response statusCode] == 200){ //注意判断statusCode,具体值可以根据实际情况补充
//将数据缓存
[self writeDataOfUrlString:request.URL.absoluteString];
}
[super storeCachedResponse:cachedResponse forRequest:request];
}
@end
完成MyURLCache的实现后,咱们在AppDelegate中程序启动后,立即调用下面方法设置全局的NSURLCache
MyURLCache * cache = [[MyURLCache alloc] init];
[NSURLCache setSharedURLCache:cache];
欢迎关注iOS开发之道
的微博和微信帐号,一起交流学习。 微博:iOS开发之道 微信:ioszhidao