一開始我以為下面這段程式碼就能讓 UIWebView 自動管理快取:
testCache = [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024 * 12
diskCapacity:1024 * 1024 * 120
diskPath:@"Assitant.db"];
[NSURLCache setSharedURLCache:testCache];
結果圖片每次還是在重新載入。120MB 的磁碟配額怎麼可能不夠?研究了半天也搞不清楚是用法不對,還是有別的因素在背後作梗。
查了資料之後才發現,這件事恐怕得自己實作快取的讀寫。於是動手寫了一個,花了三天。一開始總覺得寫入成功了,但下次進入又找不到檔案,折騰到第三天,才發現是被自己寫的刪除邏輯清掉了——那段清理程式碼每次 App 啟動都會跑一次,實在很無奈。
網路上的資料看起來很多,實際挑起來五花八門:不是過時了,就是不太可靠(本文撰寫於 2014 年,環境為 iOS 7)。
MyUrlCache.h
#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
#import "MyUrlCache.h"
#import "Utils.h"
@implementation MyUrlCache
#define WILL_BE_CACHED_EXTS @".jpg.png.gif.bmp.ico"
static NSString *spath;
static NSFileManager *fileManager;
static NSString *dirName = @"httpCache";
static 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 {
}
- (void)doRemoveAllCachedResponses {
if (spath != nil) {
[fileManager removeItemAtPath:spath error:nil];
}
}
- (NSString *)getMineType:(NSURLRequest *)request {
NSString *ext = [[request URL] absoluteString].pathExtension;
if (ext != nil) {
if ([ext compare:@"htm"] || [ext compare:@"html"]) return @"text/html";
return [NSString stringWithFormat:@"image/%@", ext];
}
return @"";
}
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSString *filename = [self getCachedFileName:request];
if (spath != nil && filename.length > 0) {
filename = [spath stringByAppendingPathComponent:filename];
if ([fileManager fileExistsAtPath:filename]) {
NSData *data = [NSData dataWithContentsOfFile:filename];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
MIMEType:[self getMineType:request]
expectedContentLength:data.length
textEncodingName:nil];
return [[NSCachedURLResponse alloc] initWithResponse:response data:data];
}
}
return nil;
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse
forRequest:(NSURLRequest *)request {
NSString *filename = [self getCachedFileName:request];
if (spath != nil && filename.length > 0) {
if (![fileManager fileExistsAtPath:filename]) {
[Utils writeFileToDirWithDirType:dirName
dirType:dirType
fileName:filename
DATA:cachedResponse.data];
}
}
}
- (NSString *)getCachedFileName:(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
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
@interface Utils : NSObject
+(void)writeFile:(NSString *)filePath data:(NSString *)_data;
+(NSString *)readFile:(NSString *)filePath;
+(NSString *)md5:(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 中的關鍵片段:
#import "Utils.h"
#import <zlib.h>
@implementation Utils
// MD5(32 位小寫),用來把 URL 轉成安全的檔名
+ (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;
}
// 依指定目錄層級寫入檔案
+(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];
}
// 解壓 gzip / deflate 資料
+(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) {
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;
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;
if (done) {
[decompressed setLength:strm.total_out];
return [NSData dataWithData:decompressed];
}
return nil;
}
@end
在 viewDidAppear: 中掛上自訂快取:
testCache = [[MyUrlCache alloc] initWithMemoryCapacity:1024 * 1024 * 12
diskCapacity:1024 * 1024 * 120
diskPath:@"jiayuanAssitant.db"];
[testCache initilize];
[NSURLCache setSharedURLCache:testCache];
iOS 模擬器的檔案系統位置在:
/Users/使用者名稱/Library/Application Support/iPhone Simulator
因為一直只在真機上除錯,連快取資料夾到底有沒有被建立都無從確認,白白糾結了三天。到模擬器上打開那個目錄一看,原因立刻水落石出。往後遇到檔案系統相關的疑難,先確認路徑再懷疑程式碼,能省下不少時間。