iOS如何实现网页缓存(实现webView的缓存)

楼主提供一个最简单的方法:

以下代码直接复制即可使用.


viewDidLoad里边代码如下:_urlStr为网页链接

    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];

    NSString * path = [cachesPathstringByAppendingString:[NSStringstringWithFormat:@"/Caches/%lu.html",(unsignedlong)[_urlStrhash]]];

    NSString *htmlString = [NSStringstringWithContentsOfFile:pathencoding:NSUTF8StringEncodingerror:nil];

    

    if (!(htmlString ==nil || [htmlString isEqualToString:@""])) {

        [_webViewloadHTMLString:htmlStringbaseURL:[NSURLURLWithString:_urlStr]];

    }else{

        NSURL *url = [NSURLURLWithString:_urlStr];

        NSURLRequest *request = [NSURLRequestrequestWithURL:url];

        [_webViewloadRequest:request];

        [selfwriteToCache];

    }


/**

 * 网页缓存写入文件

 */

- (void)writeToCache

{

    NSString * htmlResponseStr = [NSStringstringWithContentsOfURL:[NSURLURLWithString:_urlStr]encoding:NSUTF8StringEncodingerror:Nil];

    //创建文件管理器

    NSFileManager *fileManager = [[NSFileManageralloc]init];

    //获取document路径

    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,      NSUserDomainMask, YES) objectAtIndex:0];

    [fileManager createDirectoryAtPath:[cachesPathstringByAppendingString:@"/Caches"]withIntermediateDirectories:YESattributes:nilerror:nil];

    //写入路径

    NSString * path = [cachesPathstringByAppendingString:[NSStringstringWithFormat:@"/Caches/%lu.html",(unsignedlong)[_urlStrhash]]];

    

    [htmlResponseStr writeToFile:pathatomically:YESencoding:NSUTF8StringEncodingerror:nil];

}


阅读更多
个人分类: iOS遇到的问题
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭