At first I thought:
Testcache = [[Nsurlcache alloc]initwithmemorycapacity:1024*1024*12 diskcapacity:1024*1024*120 diskPath:@] Assitant.db "]; [Nsurlcache Setsharedurlcache:testcache];
Can let WebView automatically control the cache, did not expect the picture or every time the reload. Really can't think of, 120M still save? I don't know if it's my usage or not.
Later, after a review, found that it seems to implement the cache read and write! So wrote a, spent three days, began to always find it seems to write success, but again into there is no. After 3 days only to find that it was deleted by me, inside the deletion function, each time the program starts will be deleted, no language.
Online information is indeed a lot, a variety of, is not outdated, is not reliable (this article write with 2014-11-08 22:13,ios7).
On the code, using the method at the bottom.
myurlcache.h// com.lcst.minibrowser//// Created by Lein on 14-11-5.// Copyright (c) 2014 Lein. All rights reserved.//#import <Foundation/Foundation.h> @interface myurlcache:nsurlcache-(nscachedurlresponse *) Cachedresponseforrequest: (Nsurlrequest *) request;-(void) Storecachedresponse: (Nscachedurlresponse *) Cachedresponse forrequest: (Nsurlrequest *) request;-(void) initilize;-(void) doremoveallcachedresponses; @end
myurlcache.m//com.lcst.minibrowser////Created by Lein on 14-11-5.//Copyright (c) 2014 Lein. All rights reserved.//#import "MyUrlCache.h" #import "Utils.h" @implementation myurlcache#define will_be_cached_exts ". Jpg.png.gif.bmp.ico "#define debugp//#define WILL_BE_CACHED_EXTS". html "NSString * spath; Nsfilemanager *filemanager; nsstring* [email protected] "HttpCache"; Nsinteger dirtype = 0;-(void) initilize{FileManager = [Nsfilemanager Defaultmanager]; Nsarray *paths = Nssearchpathfordirectoriesindomains ((dirtype==0? NSDocumentDirectory: (dirtype==1? nslibrarydirectory:nscachesdirectory)), Nsuserdomainmask, YES); spath =[paths objectatindex:0]; [FileManager Changecurrentdirectorypath:spath]; spath = [spath stringbyappendingpathcomponent:dirname]; [FileManager Changecurrentdirectorypath:spath];} -(void) removeallcachedresponses{//Cannot execute doremoveallcachedresponses here, otherwise you will delete}-(void) You write doremoveallcachedresponses{if (spath!=nil) {[FileManager REMoveitematpath:spath Error:nil]; }}-(NSString *) Getminetype: (Nsurlrequest *) request{nsstring *ext = [[Request URL] absolutestring].pathextension; if (ext!=nil) {nsstring* str; if ([ext compare:@ "htm"]| | [ext compare:@ "html"]) str = @ "text/html"; else str = [NSString stringwithformat:@ "image/%@", ext]; return str; } return @ "";} -(Nscachedurlresponse *) Cachedresponseforrequest: (Nsurlrequest *) Request {nsstring* filename = [self Getcachedfilenam E:request]; if (Spath!=nil && filename.length>0) {filename = [spath stringbyappendingpathcomponent:filename]; if ([FileManager Fileexistsatpath:filename]) {#ifdef DEBUGP NSLog (@ "\ n" Note:::: Cache used:%@ ", [[Request URL] Abso Lutestring]); #endif nsdata* data = [NSData datawithcontentsoffile:filename]; Nsurlresponse *response = [[Nsurlresponse alloc] initwithurl:request. URL mimetype:[self Getminetype:request] ExpectedcontentlenGth:data.length Textencodingname:nil]; nscachedurlresponse* cachedresponse = [[Nscachedurlresponse alloc] Initwithresponse:response Data:data]; return cachedresponse; }} return nil; }-(void) Storecachedresponse: (Nscachedurlresponse *) cachedresponse forrequest: (nsurlrequest *) Request {NSString* filename = [self getcachedfilename:request]; if (Spath!=nil && filename.length>0) {if (![ FileManager Fileexistsatpath:filename]) {filename = [Utils writefiletodirwithdirtype:dirname dirtype:dirtype fi Lename:filename DATA:cachedResponse.data]; #ifdef DEBUGP NSLog (@ "\ n Note:::: Write Cache file =%@", filename); #endif} } #ifdef DEBUGP Else NSLog (@ "\ n Note:::: Do not cache:%@", [[Request URL] absolutestring]); #endif}-(nsstring*) GETCACHEDFI Lename: (nsurlrequest *) request{nsstring *ext = [[Request URL] absolutestring].pathextension; if (Ext!=nil) {if ([@WILL_BE_CACHED_EXTS rangeOfString:ext.lowercaseString].length>0) {return [NSString stringwithformat:@ "%@.%@", [Utils md5:[[request URL] absolutestring]], ext ]; }} return @ "";} @end
utils.h// com.lcst.minibrowser//// Created by Lein on 14-8-4.// Copyright (c) 2014 Lein. All rights reserved.//#import <Foundation/Foundation.h> #import <CommonCrypto/CommonDigest.h> @interface utils:nsobject+ (void) WriteFile: (NSString *) FilePath data: (NSString *) _data;+ (NSString *) ReadFile: (NSString *) Filepa th;+ (NSString *) MD5: (NSString *) str;+ (NSString *) Replacestringbetween: (NSString *) startstr endstring: (NSString *) Endstring Str: (NSString *) str;+ (Nsinteger) getts;+ (NSData *) Uncompresszippeddata: (NSData *) compresseddata;+ ( nsstring*) Writefiletodirwithdirtype: (nsstring*) dirname Dirtype: (nsinteger) type filename: (nsstring*) filename DATA :(NSData *) data;+ (nsdata*) Readfilefromdirwithdirtype: (nsstring*) dirname Dirtype: (nsinteger) type fileName: ( nsstring*) filename; @end
utils.m//com.lcst.minibrowser////Created by Lein on 14-8-4.//Copyright (c) 2014 Lein. All rights reserved.//#import "Utils.h" #import <zlib.h> @implementation utils+ (void) WriteFile: (NSString *) FilePath Data: (NSString *) _data{Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUserDoma Inmask, YES); nsstring* fileName = [[Paths objectatindex:0] stringbyappendingpathcomponent:filepath]; Use this method to determine whether the current file exists, if it does not exist, create a file Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager]; if (![ FileManager Fileexistsatpath:filename]) {NSLog (@ "File%@ not exists!", fileName); [FileManager createfileatpath:filename Contents:nil Attributes:nil]; }else NSLog (@ "File%@ exists!", fileName); NSLog (@ "File%@ would write!", fileName); [_data writetofile:filename atomically:yes encoding:nsutf8stringencoding error:nil];} + (NSString *) Replacestringbetween: (NSString *) startstr endstring: (NSString *) endstring Str: (NSSTring *) str{nsrange range1 = [str rangeofstring:startstr]; int len = str.length-range1.location-range1.length; Nsrange range2 = [str rangeofstring:endstring options:nscaseinsensitivesearch Range:nsmakerange (range1.location+ Range1.length, Len)]; int start =range1.length+range1.location; Len = range2.location-(range1.length+range1.location); nsstring* toreplace = [str substringwithrange:nsmakerange (Start, Len)]; return [str stringbyreplacingoccurrencesofstring:toreplace withstring:@ "];} + (NSString *) ReadFile: (NSString *) filepath{Nsarray *paths = Nssearchpathfordirectoriesindomains (nsdocumentdirectory , Nsuserdomainmask, YES); nsstring* fileName = [[Paths Objectatindex:0]stringbyappendingpathcomponent:filepath]; NSLog (@ "File%@ would be read!", fileName); nsstring* myString = [NSString stringwithcontentsoffile:filename usedencoding:null error:null]; return myString;} MD5 32-bit encryption (lowercase) + (NSString *) MD5: (NSString *) srcstring {const char*CSTR = [srcstring utf8string]; unsigned char digest[cc_md5_digest_length]; CC_MD5 (CStr, (Cc_long) strlen (CSTR), Digest); nsmutablestring *result = [nsmutablestring stringwithcapacity:cc_md5_digest_length * 2]; for (int i = 0; i < cc_md5_digest_length; i++) [Result AppendFormat: @ "%02x", Digest[i]]; return result;} + (Nsinteger) getts{nsdate *date = [NSDate Date]; Nstimeinterval timestamp = [date timeIntervalSince1970]; Return (Nsinteger) timestamp;} + (NSData *) Uncompresszippeddata: (NSData *) compresseddata{if ([compresseddata length] = = 0) return compresseddata; unsigned full_length = [compresseddata length]; unsigned half_length = [Compresseddata length]/2; Nsmutabledata *decompressed = [Nsmutabledata datawithlength:full_length + half_length]; BOOL done = NO; int status; Z_stream STRM; strm.next_in = (BYTEF *) [compresseddata bytes]; strm.avail_in = [Compresseddata length]; strm.total_out = 0; Strm.zalloc = Z_null; Strm.zfree = Z_null; if (InflateInit2 (&STRM, (15+32)) = Z_OK) return nil; while (!done) {//Do sure we have enough and reset the lengths. if (strm.total_out >= [decompressed length]) {[decompressed increaselengthby:half_length]; } strm.next_out = [decompressed mutablebytes] + strm.total_out; Strm.avail_out = [decompressed length]-strm.total_out; Inflate another chunk. Status = Inflate (&STRM, Z_sync_flush); if (status = = Z_stream_end) {done = YES; } else if (status! = Z_OK) {break; }} if (Inflateend (&STRM)! = Z_OK) return nil; Set real length. if (done) {[decompressed setLength:strm.total_out]; return [NSData datawithdata:decompressed]; } else {return nil; }}+ (nsstring*) Writefiletodirwithdirtype: (nsstring*) dirname Dirtype: (nsinteger) Type FilenaMe: (nsstring*) filename DATA: (NSData *) data{nsfilemanager* filemanager = [Nsfilemanager Defaultmanager]; Nsarray *paths = Nssearchpathfordirectoriesindomains ((type==0? NSDocumentDirectory: (type==1? nslibrarydirectory:nscachesdirectory)), Nsuserdomainmask, YES); nsstring* spath =[paths objectatindex:0]; [FileManager Changecurrentdirectorypath:spath]; if (dirname.length>0) {[FileManager createdirectoryatpath:dirname withintermediatedirectories:yes Attributes:nil Error:nil]; spath = [NSString stringwithformat:@ "%@/%@/%@", spath, dirname, filename]; }else spath = [NSString stringwithformat:@ "%@/%@", spath, filename]; [FileManager Createfileatpath:spath contents:data Attributes:nil]; return spath;} + (nsdata*) Readfilefromdirwithdirtype: (nsstring*) dirname Dirtype: (nsinteger) type fileName: (nsstring*) filename{ Nsarray *paths = Nssearchpathfordirectoriesindomains ((type==0? NSDocumentDirectory: (type==1? Nslibrarydirectory:nscachesdirectory)), Nsuserdomainmask, YES); nsstring* spath =[paths objectatindex:0]; if (dirname.length>0) spath = [NSString stringwithformat:@ "%@/%@/%@", spath, dirname, filename]; else spath = [NSString stringwithformat:@ "%@/%@", spath, filename]; return [[NSData alloc] initwithcontentsoffile:spath];} @end
Use, in Viewdidappear:
Testcache = [[Myurlcache alloc]initwithmemorycapacity:1024*1024*12 diskcapacity:1024*1024*120 diskPath:@] Jiayuanassitant.db "]; [Testcache initilize]; [Nsurlcache Setsharedurlcache:testcache];
By the way, the iOS simulator's hard disk location in:/users/mac user name/library/application Support/iphone Simulator; because it has been on the real machine, even the folder is not known, so tangled up for three days, Look at the simulator and find out why.
IOS UIWebView cache files.