IOS UIWebview cache file.
Initially I thought:
testCache = [[NSURLCache alloc]initWithMemoryCapacity:1024*1024*12 diskCapacity:1024*1024*120 diskPath:@"Assitant.db"]; [NSURLCache setSharedURLCache:testCache];
The webview can automatically control the cache. I didn't expect the image to be reloaded every time. I can't figure it out, but I can't save MB? I don't know if it's correct.
After some queries, I found that I had to implement cache read/write by myself! So it took three days to write one. At first, I found that the write operation was successful, but I entered whether or not it was successful. After three days, I found that the function was deleted by myself. The function will be deleted every time the program starts.
There are indeed a lot of materials on the Internet, varied, either out of date or unreliable (this article is written at, iOS7 ).
The code is used at the bottom.
//// MyUrlCache. h // com. lcst. miniBrowser // Created by lein on 14-11-5. // Copyright (c) 2014 lein. all rights reserved. // # import
@ Interface MyUrlCache: NSURLCache-(response *) cachedResponseForRequest :( NSURLRequest *) request;-(void) storeCachedResponse :( response *) cachedResponse forRequest :( NSURLRequest *) request; -(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 * dirName = @" httpCache "; NSInteger dirType = 0;-(void) initili Ze {fileManager = [NSFileManager defaultManager]; NSArray * paths = NSSearchPathForDirectoriesInDomains (dirType = 0? NSDocumentDirectory :( dirType = 1? NSLibraryDirectory: NSCachesDirectory), NSUserDomainMask, YES); spath = [paths objectAtIndex: 0]; [fileManager attributes: spath]; spath = [spath attributes: dirName]; [fileManager changeCurrentDirectoryPath: spath];}-(void) removeAllCachedResponses {// you cannot execute doRemoveAllCachedResponses here; otherwise, your write will be deleted each time}-(void) 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 getCachedFileName: request]; if (spath! = Nil & filename. length> 0) {filename = [spath stringByAppendingPathComponent: filename]; if ([fileManager fileExistsAtPath: filename]) {# ifdef DEBUGP NSLog (@ "\ n Note :::: cache used: % @ ", [[request URL] absoluteString]); # endif NSData * data = [NSData dataWithContentsOfFile: filename]; NSURLResponse * response = [[NSURLResponse alloc] initWithURL: request. URL MIMEType: [self getMineType: request] expectedContentLe Ngth: 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 fileName: filename DATA: cachedResponse. data]; # ifdef DEBUGP NSLog (@ "\ n Note: Write cache file =%@", filename ); # endif }# ifdef DEBUGP else NSLog (@ "\ n Note: no cache: % @", [[request URL] absoluteString]); # endif}-(NSString *) getCachedFileName :( NSURLRequest *) request {NSString * ext = [[request URL] absoluteStri Ng]. 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
# Import
@ Interface Utils: NSObject + (void) writeFile :( NSString *) filePath data :( NSString *) _ data; + (NSString *) readFile :( NSString *) filePath; + (NSString *) md5 :( NSString *) str; + (NSString *) replaceStringBetween :( NSString *) startStr EndString :( NSString *) endString Str :( NSString *) str; + (NSInteger) getTs; + (NSData *) uncompressZippedData :( NSData *) compressedData; + (NSString *) Partition :( 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
@ Implementation Utils + (void) writeFile :( NSString *) filePath data :( NSString *) _ data {NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); NSString * fileName = [[paths objectAtIndex: 0] stringByAppendingPathComponent: filePath]; // This method is used to determine whether the current file exists. If not, 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 % @ will write! ", FileName); [_ data writeToFile: fileName atomically: YES encoding: NSUTF8StringEncoding error: nil];} + (NSString *) replaceStringBetween :( NSString *) startStr EndString :( NSString *) endString Str :( NSString *) str {nsange range1 = [str rangeOfString: startStr]; int len = str. length-range1.location-range1.length; nsange range2 = [str rangeOfString: endString options: NSCaseInsensitiveSearch range: NSM AkeRange (range1.location + range1.length, len)]; int start = range1.length + range1.location; len = range2.location-(range1.length + range1.location); NSString * toReplace = [str kernel: NSMakeRange (start, len)]; return [str failed: toReplace withString: @ ""] ;}+ (NSString *) readFile :( NSString *) filePath {NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumen TDirectory, NSUserDomainMask, YES); NSString * fileName = [[paths objectAtIndex: 0] stringByAppendingPathComponent: filePath]; NSLog (@ "File % @ will be read! ", FileName); NSString * myString = [NSString stringWithContentsOfFile: fileName usedEncoding: NULL error: NULL]; return myString;} // md5 32-bit encryption (lower case) + (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_DIG EST_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; using * decompressed = [using 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. zarloc = Z_NULL; strm. zfree = Z_NULL; if (inflateInit2 (& strm, (15 + 32 ))! = Z_ OK) return nil; while (! Done) {// Make sure we have enough room 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 (stat Us! = 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 *) delimiter :( NSString *) dirname dirType :( NSInteger) type fileName :( NSString *) filename DATA :( NSData *) data {NSFileManager * fileManager = [NSFileManager defaultManager]; NSArray * paths = NSSearchPathForDirectories InDomains (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
Used 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 hard drive of the iOS Simulator is located at:/Users/mac username/Library/Application Support/iPhone Simulator; because it has been on a real machine, I didn't even know why the folder was created, so I had to spend three days entangled. I checked the cause on the simulator.