功能需求html
這個緩存機制知足下面這些功能。web
一、能夠將數據緩存到本地磁盤。緩存
二、能夠判斷一個資源是否已經被緩存。若是已經被緩存,在請求相同的資源,先到本地磁盤搜索。session
三、能夠判斷文件緩存何時過時。這裏爲了簡單起見這裏,咱們在請求url資源的時候,給每次請求的文件設定一個過時的時間。併發
四、能夠實現:若是文件已經被緩存,並且沒有過時,這將本地的數據返回,不然從新請求url。ide
五、能夠實現:若是文件下載不成功或者下載沒有完成,下次打開程序的時候,移除這些沒有成功或者沒有下載完成的文件。測試
六、能夠實現:同時請求或者下載多個資源。網站
設計實現:ui
一、設計一個CacheItem類,用來請求一個web鏈接,它的一個實例表示一個緩存項。這個CacheItem類,須要一個url建立一個NSURLConnection,去請求web資源。使用CacheItem類主要用來請求web資源。atom
/* ---------緩存項-------------- */
@interface CacheItem : NSObject {
@public
id<CacheItemDelegate> delegate;
//web地址
NSString *remoteURL;
@private
//是否正在下載
BOOL isDownloading;
//NSMutableData對象
NSMutableData *connectionData;
//NSURLConnection對象
NSURLConnection *connection;
}
/* -------------------------- */
@property (nonatomic, assign) id<CacheItemDelegate> delegate;
@property (nonatomic, retain) NSString *remoteURL;
@property (nonatomic, assign) BOOL isDownloading;
@property (nonatomic, retain) NSMutableData *connectionData;
@property (nonatomic, retain) NSURLConnection *connection;
/* ----------開始下載方法----------- */
- (BOOL) startDownloadingURL:(NSString *)paramRemoteURL;
@end
二、在NSURLConnection開始請求以前,調用CachedDownloadManager類,來搜索和管理本地的緩存文件。將緩存文件的狀況保存到一個字典類中。這個字典設計以下:
{
"http://www.cnn.com" = {
DownloadEndDate = "2011-08-02 07:51:57 +0100";
DownloadStartDate = "2011-08-02 07:51:55 +0100";
ExpiresInSeconds = 20;
ExpiryDate = "2011-08-02 07:52:17 +0100";
LocalURL = "/var/mobile/Applications/ApplicationID/Documents/
httpwww.cnn.com.cache";
};
"http://www.baidu.com" = {
DownloadEndDate = "2011-08-02 07:51:49 +0100";
DownloadStartDate = "2011-08-02 07:51:44 +0100";
ExpiresInSeconds = 20;
ExpiryDate = "2011-08-02 07:52:09 +0100";
LocalURL = "/var/mobile/Applications/ApplicationID/Documents/
httpwww.oreilly.com.cache";
};
}
上面這個字典裏面嵌套了字典。裏面那層字典表示一個緩存項的緩存信息:下載結束時間、下載開始時間、緩存有效時間、緩存過時時間、緩存到本地的路徑。
下面看下CachedDownloadManager類。用它來實現和封裝咱們的緩存策略。
/* -----------CachedDownloadManager-------------- */
@interface CachedDownloadManager : NSObject
<CacheItemDelegate> {
@public
id<CachedDownloadManagerDelegate> delegate;
@private
//記錄緩存數據的字典
NSMutableDictionary *cacheDictionary;
//緩存的路徑
NSString *cacheDictionaryPath;
}
@property (nonatomic, assign)
id<CachedDownloadManagerDelegate> delegate;
@property (nonatomic, copy)
NSMutableDictionary *cacheDictionary;
@property (nonatomic, retain)
NSString *cacheDictionaryPath;
/* 保持緩存字典 */
- (BOOL) saveCacheDictionary;
/* 公有方法:下載 */
- (BOOL) download:(NSString *)paramURLAsString
urlMustExpireInSeconds:(NSTimeInterval)paramURLMustExpireInSeconds
updateExpiryDateIfInCache:(BOOL)paramUpdateExpiryDateIfInCache;
/* -------------------------- */
@end
從上面代碼能夠看出,這個管理緩存的類中,有一個緩存字典:cacheDictionary,用來表示全部資源的緩存狀況;cacheDictionaryPath用來表示緩存的路徑;saveCacheDictionary用來將緩存字典歸檔到本地文件中。download:urlMustExpireInSeconds:updateExpiryDateIfInCache是一個公共接口,經過傳遞url、緩存過時時間、是否更新緩存過時時間三個參數來方便的使用,實現咱們的緩存策略。
三、若是這個文件已經被下載,並且沒有過時,則從本地獲取文件的數據。若是文件已通過期,則從新下載。咱們經過download:urlMustExpireInSeconds:updateExpiryDateIfInCache方法來實現,主要看這個方法的代碼:
/* ---------下載-------------- */
- (BOOL) download:(NSString *)paramURLAsString
urlMustExpireInSeconds:(NSTimeInterval)paramURLMustExpireInSeconds
updateExpiryDateIfInCache:(BOOL)paramUpdateExpiryDateIfInCache{
BOOL result = NO;
if (self.cacheDictionary == nil ||
[paramURLAsString length] == 0){
return(NO);
}
paramURLAsString = [paramURLAsString lowercaseString];
//根據url,從字典中獲取緩存項的相關數據
NSMutableDictionary *itemDictionary =
[self.cacheDictionary objectForKey:paramURLAsString];
/* 使用下面這些變量幫助咱們理解緩存邏輯 */
//文件是否已經被緩存
BOOL fileHasBeenCached = NO;
//緩存是否過時
BOOL cachedFileHasExpired = NO;
//緩存文件是否存在
BOOL cachedFileExists = NO;
//緩存文件可否被加載
BOOL cachedFileDataCanBeLoaded = NO;
//緩存文件數據
NSData *cachedFileData = nil;
//緩存文件是否徹底下載
BOOL cachedFileIsFullyDownloaded = NO;
//緩存文件是否已經下載
BOOL cachedFileIsBeingDownloaded = NO;
//過時時間
NSDate *expiryDate = nil;
//下載結束時間
NSDate *downloadEndDate = nil;
//下載開始時間
NSDate *downloadStartDate = nil;
//本地緩存路徑
NSString *localURL = nil;
//有效時間
NSNumber *expiresInSeconds = nil;
NSDate *now = [NSDate date];
if (itemDictionary != nil){
fileHasBeenCached = YES;
}
//若是文件已經被緩存,則從緩存項相關數據中獲取相關的值
if (fileHasBeenCached == YES){
expiryDate = [itemDictionary
objectForKey:CachedKeyExpiryDate];
downloadEndDate = [itemDictionary
objectForKey:CachedKeyDownloadEndDate];
downloadStartDate = [itemDictionary
objectForKey:CachedKeyDownloadStartDate];
localURL = [itemDictionary
objectForKey:CachedKeyLocalURL];
expiresInSeconds = [itemDictionary
objectForKey:CachedKeyExpiresInSeconds];
//若是下載開始和結束時間不爲空,表示文件所有被下載
if (downloadEndDate != nil &&
downloadStartDate != nil){
cachedFileIsFullyDownloaded = YES;
}
/* 若是expiresInSeconds不爲空,downloadEndDate爲空,表示文件已經正在下載 */
if (expiresInSeconds != nil &&
downloadEndDate == nil){
cachedFileIsBeingDownloaded = YES;
}
/* 判斷緩存是否過時 */
if (expiryDate != nil &&
[now timeIntervalSinceDate:expiryDate] > 0.0){
cachedFileHasExpired = YES;
}
if (cachedFileHasExpired == NO){
/* 若是緩存文件沒有過時,加載緩存文件,而且更新過時時間 */
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:localURL] == YES){
cachedFileExists = YES;
cachedFileData = [NSData dataWithContentsOfFile:localURL];
if (cachedFileData != nil){
cachedFileDataCanBeLoaded = YES;
} /* if (cachedFileData != nil){ */
} /* if ([fileManager fileExistsAtPath:localURL] == YES){ */
[fileManager release];
/* 更新緩存時間 */
if (paramUpdateExpiryDateIfInCache == YES){
NSDate *newExpiryDate =
[NSDate dateWithTimeIntervalSinceNow:
paramURLMustExpireInSeconds];
NSLog(@"Updating the expiry date from %@ to %@.",
expiryDate,
newExpiryDate);
[itemDictionary setObject:newExpiryDate
forKey:CachedKeyExpiryDate];
NSNumber *expires =
[NSNumber numberWithFloat:paramURLMustExpireInSeconds];
[itemDictionary setObject:expires
forKey:CachedKeyExpiresInSeconds];
}
} /* if (cachedFileHasExpired == NO){ */
}
if (cachedFileIsBeingDownloaded == YES){
NSLog(@"這個文件已經正在下載...");
return(YES);
}
if (fileHasBeenCached == YES){
if (cachedFileHasExpired == NO &&
cachedFileExists == YES &&
cachedFileDataCanBeLoaded == YES &&
[cachedFileData length] > 0 &&
cachedFileIsFullyDownloaded == YES){
/* 若是文件有緩存並且沒有過時 */
NSLog(@"文件有緩存並且沒有過時.");
[self.delegate
cachedDownloadManagerSucceeded:self
remoteURL:[NSURL URLWithString:paramURLAsString]
localURL:[NSURL URLWithString:localURL]
aboutToBeReleasedData:cachedFileData
isCachedData:YES];
return(YES);
} else {
/* 若是文件沒有被緩存,獲取緩存失敗 */
NSLog(@"文件沒有緩存.");
[self.cacheDictionary removeObjectForKey:paramURLAsString];
[self saveCacheDictionary];
} /* if (cachedFileHasExpired == NO && */
} /* if (fileHasBeenCached == YES){ */
/* 去下載文件 */
NSNumber *expires =
[NSNumber numberWithFloat:paramURLMustExpireInSeconds];
NSMutableDictionary *newDictionary =
[[[NSMutableDictionary alloc] init] autorelease];
[newDictionary setObject:expires
forKey:CachedKeyExpiresInSeconds];
localURL = [paramURLAsString
stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
localURL = [localURL stringByReplacingOccurrencesOfString:@"://"
withString:@""];
localURL = [localURL stringByReplacingOccurrencesOfString:@"/"
withString:@"{1}quot;];
localURL = [localURL stringByAppendingPathExtension:@"cache"];
NSString *documentsDirectory =
[self documentsDirectoryWithTrailingSlash:NO];
localURL = [documentsDirectory
stringByAppendingPathComponent:localURL];
[newDictionary setObject:localURL
forKey:CachedKeyLocalURL];
[newDictionary setObject:now
forKey:CachedKeyDownloadStartDate];
[self.cacheDictionary setObject:newDictionary
forKey:paramURLAsString];
[self saveCacheDictionary];
CacheItem *item = [[[CacheItem alloc] init] autorelease];
[item setDelegate:self];
[item startDownloadingURL:paramURLAsString];
return(result);
}
四、下面咱們設計緩存項下載成功和失敗的兩個委託方法:
@protocol CacheItemDelegate <NSObject>
//下載成功執行該方法
- (void) cacheItemDelegateSucceeded
:(CacheItem *)paramSender
withRemoteURL:(NSURL *)paramRemoteURL
withAboutToBeReleasedData:(NSData *)paramAboutToBeReleasedData;
//下載失敗執行該方法
- (void) cacheItemDelegateFailed
:(CacheItem *)paramSender
remoteURL:(NSURL *)paramRemoteURL
withError:(NSError *)paramError;
@end
當咱們下載成功的時候,修改緩存字典中的下載時間,表示已經下載完成,並且須要將請求的資源數據緩存到本地:
//緩存項的委託方法
- (void) cacheItemDelegateSucceeded:(CacheItem *)paramSender
withRemoteURL:(NSURL *)paramRemoteURL
withAboutToBeReleasedData:(NSData *)paramAboutToBeReleasedData{
//從緩存字典中獲取該緩存項的相關數據
NSMutableDictionary *dictionary =
[self.cacheDictionary objectForKey:[paramRemoteURL absoluteString]];
//取當前時間
NSDate *now = [NSDate date];
//獲取有效時間
NSNumber *expiresInSeconds = [dictionary
objectForKey:CachedKeyExpiresInSeconds];
//轉換成NSTimeInterval
NSTimeInterval expirySeconds = [expiresInSeconds floatValue];
//修改字典中緩存項的下載結束時間
[dictionary setObject:[NSDate date]
forKey:CachedKeyDownloadEndDate];
//修改字典中緩存項的緩存過時時間
[dictionary setObject:[now dateByAddingTimeInterval:expirySeconds]
forKey:CachedKeyExpiryDate];
//保存緩存字典
[self saveCacheDictionary];
NSString *localURL = [dictionary objectForKey:CachedKeyLocalURL];
/* 將下載的數據保持到磁盤 */
if ([paramAboutToBeReleasedData writeToFile:localURL
atomically:YES] == YES){
NSLog(@"緩存文件到磁盤成功.");
} else{
NSLog(@"緩存文件到磁盤失敗.");
}
//執行緩存管理的委託方法
[self.delegate
cachedDownloadManagerSucceeded:self
remoteURL:paramRemoteURL
localURL:[NSURL URLWithString:localURL]
aboutToBeReleasedData:paramAboutToBeReleasedData
isCachedData:NO];
}
若是下載失敗咱們須要從緩存字典中移除改緩存項:
//緩存項失敗失敗的委託方法
- (void) cacheItemDelegateFailed:(CacheItem *)paramSender
remoteURL:(NSURL *)paramRemoteURL
withError:(NSError *)paramError{
/* 從緩存字典中移除緩存項,併發送一個委託 */
if (self.delegate != nil){
NSMutableDictionary *dictionary =
[self.cacheDictionary
objectForKey:[paramRemoteURL absoluteString]];
NSString *localURL = [dictionary
objectForKey:CachedKeyLocalURL];
[self.delegate
cachedDownloadManagerFailed:self
remoteURL:paramRemoteURL
localURL:[NSURL URLWithString:localURL]
withError:paramError];
}
[self.cacheDictionary
removeObjectForKey:[paramRemoteURL absoluteString]];
}
這樣就基本上完成了咱們須要的功能,下面看看咱們如何使用咱們設計的緩存功能。
例子場景:
咱們用一個UIWebView來顯示stackoverflow這個網站,咱們在這個網站的內容緩存到本地20秒,若是在20秒內用戶去請求該網站,則從本地文件中獲取內容,不然過了20秒,則從新獲取數據,並緩存到本地。
在界面上拖放一個button和一個webview控件
- (void)viewDidLoad {
[super viewDidLoad];
[self setTitle:@"本地緩存測試"];
CachedDownloadManager *newManager = [[CachedDownloadManager alloc] init];
self.downloadManager = newManager;
[newManager release];
[self.downloadManager setDelegate:self];
}
在button的點擊事件中加入下面代碼,請求stackoverflow :
static NSString *url = @"http://stackoverflow.com"; [self.downloadManager download:url urlMustExpireInSeconds:20.0f updateExpiryDateIfInCache:YES];
上面的代碼表示將這個stackoverflow的緩存事件設置爲20s,而且若是在20s內有相同的請求,則從本地獲取stackoverflow的內容數據。updateExpiryDateIfInCache設置爲yes表示:在此請求的時候,緩存時間又更新爲20s,相似咱們的session。若是設置成no,則第一次請求20s以後,該緩存就過時。
請求完成以後會執行CachedDownloadManager的委託方法。咱們將數據展現在uiwebview中,代碼以下:
- (void) cachedDownloadManagerSucceeded:(CachedDownloadManager *)paramSender remoteURL:(NSURL *)paramRemoteURL localURL:(NSURL *)paramLocalURL aboutToBeReleasedData:(NSData *)paramAboutToBeReleasedData isCachedData:(BOOL)paramIsCachedData{
[webview loadData:paramAboutToBeReleasedData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://stackoverflow.com"]];
}