1. 程式人生 > >iOS如何實現網頁快取(實現webView的快取)

iOS如何實現網頁快取(實現webView的快取)

樓主提供一個最簡單的方法:

以下程式碼直接複製即可使用.

viewDidLoad裡邊程式碼如下:_urlStr為網頁連結

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

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

hash]]];

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:NSUTF8StringEncoding

error: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];

}