源码:http://files.cnblogs.com/ios8/ASIHttpRequestDemo2.zip
NSURL *url = [NSURLURLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
ASIFormDataRequest *request = [ASIFormDataRequestrequestWithURL:url];//创建数据请求对象
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:60];
// [request setDelegate:self];//设置代理
// 设置缓存--
ASIDownloadCache *cache = [[ASIDownloadCachealloc]init];//创建缓存对象
NSString *cachePath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]; //设置缓存目录,这里设置沙盒目录下的Documents目录作为缓存目录
NSLog(@"cachepath:%@",cachePath);
[cache setStoragePath:cachePath];
cache.defaultCachePolicy =ASIOnlyLoadIfNotCachedCachePolicy; //设置缓存策略
//每次请求会将上一次的请求缓存文件清除
// request.cacheStoragePolicy = ASICacheForSessionDurationCacheStoragePolicy;
//持久缓存,一直保存在本地(是持久缓存,程序下次启动,缓存仍然还在)
request.cacheStoragePolicy =ASICachePermanentlyCacheStoragePolicy;
request.downloadCache = cache;
[request startAsynchronous];//发送异步请求
//设置网络请求完成后调用的block
[request setCompletionBlock:^{
// NSLog(@"%@",request.responseHeaders);
NSData *data = request.responseData;
self.showImageView.image = [UIImageimageWithData:data];
//---------------判断数据的来源:网络 or缓存------------------
if (request.didUseCachedResponse) {
NSLog(@"数据来自缓存");
} else {
NSLog(@"数据来自网络");
}
}];
//请求失败调用的block
[request setFailedBlock:^{
NSError *error = request.error;
NSLog(@"请求网络出错:%@",error);
}];
ViewController.m
@interface ViewController (){
ASIDownloadCache *myCache;
}
修改缓存的代码:// 设置缓存--
ASIDownloadCache *cache = [[ASIDownloadCachealloc]init];//创建缓存对象
myCache = cache;
//路径
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentDirectory = [pathsobjectAtIndex:0];
NSLog(@"path-%@",documentDirectory);
//设置缓存存放路径
[myCachesetStoragePath:[documentDirectorystringByAppendingPathComponent:@"pic"]];
myCache.defaultCachePolicy =ASIOnlyLoadIfNotCachedCachePolicy; //设置缓存策略
//每次请求会将上一次的请求缓存文件清除
// request.cacheStoragePolicy = ASICacheForSessionDurationCacheStoragePolicy;
//持久缓存,一直保存在本地(是持久缓存,程序下次启动,缓存仍然还在)
request.cacheStoragePolicy =ASICachePermanentlyCacheStoragePolicy;
request.downloadCache = cache;
-----------------
打印了路径,前往文件夹,输入路径,就的到以下图示: