4、下面我们设计缓存项下载成功和失败的两个委托方法: @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]]; }
复制代码
5、加载缓存字典的时候,我们可以将没有下载完成的文件移除: //初始化缓存字典 NSString *documentsDirectory = [self documentsDirectoryWithTrailingSlash:YES]; //生产缓存字典的路径 cacheDictionaryPath = [[documentsDirectory stringByAppendingString:@"CachedDownloads.dic"] retain]; //创建一个NSFileManager实例 NSFileManager *fileManager = [[NSFileManager alloc] init]; //判断是否存在缓存字典的数据 if ([fileManager fileExistsAtPath:self.cacheDictionaryPath] == YES){ NSLog(self.cacheDictionaryPath); //加载缓存字典中的数据 NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:self.cacheDictionaryPath]; cacheDictionary = [dictionary mutableCopy]; [dictionary release]; //移除没有下载完成的缓存数据 [self removeCorruptedCachedItems]; } else { //创建一个新的缓存字典 NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; cacheDictionary = [dictionary mutableCopy]; [dictionary release]; }
复制代码 这样就基本上完成了我们需要的功能,下面看看我们如何使用我们设计的缓存功能。
例子场景:
我们用一个UIWebView来显示stackoverflow这个网站,我们在这个网站的内容缓存到本地20秒,如果在20秒内用户去请求该网站,则从本地文件中获取内容,否则过了20秒,则重新获取数据,并缓存到本地。
在界面上拖放一个button和一个webview控件,如下图。 <ignore_js_op>
这样我们可以很方便使用前面定义好的类。我们在viewDidLoad 中实例化一个CachedDownloadManager,并设置它的委托为self。当下载完成的时候,执行CachedDownloadManager的下载成功的委托方法。 - (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"]]; }
复制代码
这样我们就实现了20s的缓存。 效果:
第一次点击测试按钮: <ignore_js_op>
20s内点击按钮,程序就从本地获取数据,比较快速的就显示出该网页了。
总结:
本文通过代码和实例设计了一个iPhone应用程序本地缓存的方案。当然这个方案不是最好的,如果你有更好的思路,欢迎告诉我。 |