缓存写入文件
Posted zhangyulin311
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了缓存写入文件相关的知识,希望对你有一定的参考价值。
- (void)writeToCaches:(NSString *)url
NSString * htmlResponseStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:Nil];
//创建文件管理器
NSFileManager *fileManager = [[NSFileManager alloc]init];
//获取document路径,括号中属性为当前应用程序独享
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"] withIntermediateDirectories:YES attributes:nil error:nil];
//定义记录文件全名以及路径的字符串filePath
NSString * path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu.html",(unsigned long)[_urlStr hash]]];
[htmlResponseStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
// 取本地缓存
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString * path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu.html",(unsigned long)[_urlStr hash]]];
NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
if (!(htmlString == nil || [htmlString isEqualToString:@""]))
// 如果有缓存就取缓存,没有就请求
[_webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:_urlStr]];
else
// 新的链接走这里进行缓存
NSURL *url = [NSURL URLWithString:_urlStr];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
[_webView loadRequest:request];
[self writeToCaches:_urlStr];
以上是关于缓存写入文件的主要内容,如果未能解决你的问题,请参考以下文章