asi缓存
转载集合
一种是自己写缓存的处理,一种是采用ASIHTTPRequest中的ASIDownloadCache。根据我目前的技术水平和时间花费,我果断选择了后者,事实证明效果也很不错。下面说一下实现方法:
1、设置全局的Cache
在AppDelegate.h中添加一个全局变量
[plain]
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
ASIDownloadCache *myCache;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,retain) ASIDownloadCache *myCache;
在AppDelegate.m中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加如下代码
[plain]
//自定义缓存
ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];
self.myCache = cache;
[cache release];
//设置缓存路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
[self.myCache setStoragePath:[documentDirectory stringByAppendingPathComponent:@"resource"]];
[self.myCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
在AppDelegate.m中的dealloc方法中添加如下语句
[plain]
[myCache release];
到这里为止,就完成了全局变量的声明。
2、设置缓存策略
在实现ASIHTTPRequest请求的地方设置request的存储方式,代码如下
[plain]
NSString *str = @"http://....../getPictureNews.aspx";
NSURL *url = [NSURL URLWithString:str];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//获取全局变量
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//设置缓存方式
[request setDownloadCache:appDelegate.myCache];
//设置缓存数据存储策略,这里采取的是如果无更新或无法联网就读取缓存数据
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
request.delegate = self;
[request startAsynchronous];
3、清理缓存数据
我在这里采用的是手动清理数据的方式,在适当的地方添加如下代码,我将清理缓存放在了应用的设置模块:
[plain]
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.myCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
这里清理的是ASICachePermanentlyCacheStoragePolicy这种存储策略的缓存数据,如果更换其他的参数的话,即可清理对应存储策略的缓存数据。
另
-(void)loadURL:(NSURL*)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//ASIWebPageRequest *request= [ASIWebPageRequest requestWithURL:url];
[request setDelegate:self];
//[request setUrlReplacementMode:ASIReplaceExternalResourcesWithData];
[request setDidFailSelector:@selector(webPageFetchFailed:)];
[request setDidFinishSelector:@selector(webPageFetchSucceeded:)];
//设置缓存
[request setDownloadCache:[ASIDownloadCache sharedCache]];
//[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[request setCachePolicy:ASIAskServerIfModifiedWhenStaleCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy];
[request setDownloadDestinationPath:[[ASIDownloadCache sharedCache]pathToStoreCachedResponseDataForRequest:request]];
[request startAsynchronous];
}
- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest
{
// Obviously you should handle the error properly...
NSLog(@"%@",[theRequest error]);
NSString *path = [[NSBundle mainBundle] pathForResource:@"error1.html" ofType:nil inDirectory:@"WebResources/Error"];
NSURL *url=[NSURL fileURLWithPath:path];
[viewer loadRequest:[NSURLRequest requestWithURL:url]];
}
- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest
{
NSString *response = [NSString stringWithContentsOfFile:
[theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];
// Note we're setting the baseURL to the url of the page we downloaded. This is important!
[viewer loadHTMLString:response baseURL:[theRequest url]];
//[viewer loadHTMLString:response baseURL:nil];
}
另
ASIHTTPRequest会自动保存访问过的URL信息,并备之后用。在以下几个场景非常有用:
1,当没有网络连接的时候。
2,已下载的数据再次请求时,仅当它与本地版本不样时才进行下载。
ASIDownloadCache 设置下载缓存
它对Get请求的响应数据进行缓存(被缓存的数据必需是成功的200请求):
[ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]]; |
当设置缓存策略后,所有的请求都被自动的缓存起来。
另外,如果仅仅希望某次请求使用缓存操作,也可以这样使用:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDownloadCache:[ASIDownloadCache sharedCache]]; |
多种的缓存并存
仅仅需要创建不同的ASIDownloadCache,并设置缓存所使用的路径,并设置到需要使用的request实例中:
ASIDownloadCache *cache = [[[ASIDownloadCache alloc] init] autorelease]; [cache setStoragePath:@ "/Users/ben/Documents/Cached-Downloads" ]; [self setMyCache:cache]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDownloadCache:[self myCache]]; |
缓存策略
缓存策略是我们控制缓存行为的主要方式,如:什么时候进行缓存,缓存数据的利用方式。
以下是策略可选列表(可组合使用):
ASIUseDefaultCachePolicy | 这是一个默认的缓存策略“ASIAskServerIfModifiedWhenStaleCachePolicy”,这个很明白,见名知意(它不能与其它策略组合使用) |
---|---|
ASIDoNotReadFromCacheCachePolicy | 所读数据不使用缓存 |
ASIDoNotWriteToCacheCachePolicy | 不对缓存数据进行写操作 |
ASIAskServerIfModifiedWhenStaleCachePolicy | 默认缓存行为,request会先判断是否存在缓存数据。a, 如果没有再进行网络请求。 b,如果存在缓存数据,并且数据没有过期,则使用缓存。c,如果存在缓存数据,但已经过期,request会先进行网络请求,判断服务器版本与本地版本是 否一样,如果一样,则使用缓存。如果服务器有新版本,会进行网络请求,并更新本地缓存 |
ASIAskServerIfModifiedCachePolicy | 与默认缓存大致一样,区别仅是每次请求都会 去服务器判断是否有更新 |
ASIOnlyLoadIfNotCachedCachePolicy | 如果有缓存在本地,不管其过期与否,总会拿来使用 |
ASIDontLoadCachePolicy | 仅当有缓存的时候才会被正确执行,如果没有缓存,request将被取消(没有错误信息) |
ASIFallbackToCacheIfLoadFailsCachePolicy | 这个选项经常被用来与其它选项组合使用。请求失败时,如果有缓存当网络则返回本地缓存信息(这个在处理异常时非常有用) |
如果设置了“defaultCachePolicy”则所有的请求都会使用此缓存。 |
缓存存储方式
你可以设置缓存的数据需要保存多长时间,ASIHTTPRequest提供了两种策略:
a,ASICacheForSessionDurationCacheStoragePolicy,默认策略,基于session的缓存数据存储。当下次运行或[ASIHTTPRequest clearSession]时,缓存将失效。
b,ASICachePermanentlyCacheStoragePolicy,把缓存数据永久保存在本地,
如:
ASIHTTPRequest *request = [ ASIHTTPRequest requestWithURL:url ]; [ request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy ]; |
另外,也可以使用clearCachedResponsesForStoragePolicy来清空指定策略下的缓存数据。
缓存其它特性
设置是否按服务器在Header里指定的是否可被缓存或过期策略进行缓存:
[[ ASIDownloadCache sharedCache ] setShouldRespectCacheControlHeaders:NO ]; |
设置request缓存的有效时间:
[ request setSecondsToCache: 60 * 60 * 24 * 30 ]; // 缓存30天 |
可以判断数据是否从缓存读取:
[ request didUseCachedResponse ]; |
设置缓存所使用的路径:
[ request setDownloadDestinationPath:[[ ASIDownloadCache sharedCache ] pathToStoreCachedResponseDataForRequest:request ]]; |
实现自定义的缓存
只要简单的实现ASICacheDelegate接口就可以被用来使用。
使用代理请求
默认的情况下,ASIHTTPRequest会使用被设置的默认代理。但你也可以手动修改http代理:
// Configure a proxy server manually ASIHTTPRequest *request = [ ASIHTTPRequest requestWithURL:url ]; [ request setProxyHost:@ "192.168.0.1" ]; [ request setProxyPort: 3128 ]; // Alternatively, you can use a manually-specified Proxy Auto Config file (PAC) // (It's probably best if you use a local file) [request setPACurl:[NSURL URLWithString:@ "file:///Users/ben/Desktop/test.pac" ]]; |
ASIHTTPRequest, 请求的其它特性
iOS4中,当应用后台运行时仍然请求数据:
[ request setShouldContinueWhenAppEntersBackground:YES ]; |
是否有网络请求:
[ ASIHTTPRequest isNetworkInUse ] |
是否显示网络请求信息在status bar上:
[ ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO ]; |
设置请求超时时,设置重试的次数:
[ request setNumberOfTimesToRetryOnTimeout: 2 ]; |
KeepAlive的支持:
// Set the amount of time to hang on to a persistent connection before it should expire to 2 minutes
[ request setPersistentConnectionTimeoutSeconds:
120
];
// Disable persistent connections entirely
[ request setShouldAttemptPersistentConnection:NO ];