iOS 取出网页缓存与网页离线缓存

来源:互联网 发布:蓝牙控制小车app源码 编辑:程序博客网 时间:2024/05/16 09:58

1.取出网页缓存

在viewDidLoad中,

//有缓存就加载缓存,没缓存就从服务器加载- (void)viewDidLoad{NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];    NSString * path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu.html",(unsigned long)[[self.url absoluteString] hash]]];    NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];        if (!(htmlString ==nil || [htmlString isEqualToString:@""])) {        [self.webView loadHTMLString:htmlString baseURL:self.url];    }else{                NSURLRequest *request = [NSURLRequest requestWithURL:self.url];        [_webView loadRequest:request];        [self writeToCache];    }}

//写入缓存- (void)writeToCache{    NSString * htmlResponseStr = [NSString stringWithContentsOfURL:self.url encoding:NSUTF8StringEncoding error:Nil];    //创建文件管理器    NSFileManager *fileManager = [NSFileManager defaultManager];    //获取document路径    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];    [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];    //写入路径    NSString * path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu.html",(unsigned long)[[self.url absoluteString] hash]]];        [htmlResponseStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];}

2.网页离线缓存

网页离线缓存就是通过截取URLProtocol 来实现的。没有网络的时候会加载缓存内容,有网络或者弱网不会加载缓存。

实用的第三库:RNCachingURLProtocol


tips:

取出网页缓存,先显示缓存内容,等网页加载完毕再显示最新的网页内容。这样就不会一直Loading.界面友好


0 0
原创粉丝点击