为了减少与服务器的连接沟通次数,提高应用程序的执行速度,使用了iOS的缓存机制
#import "YoungViewController.h"
@interface YoungViewController ()<NSURLConnectionDelegate>
{
NSURLConnection * connection;
}
@end
@implementation YoungViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton * btnCache = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnCache.frame = CGRectMake(50, 50, 100, 30);
[btnCache setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[btnCache setBackgroundColor:[UIColor orangeColor]];
[btnCache setTitle:@"缓存" forState:UIControlStateNormal];
[btnCache addTarget:self action:@selector(Chcal:)forControlEvents:UIControlEventTouchUpInside];
[self.view insertSubview:btnCache atIndex:0];
}
-(void)Chcal:(id)sender
{
NSString *paramURLAsString = @"http://www.baidu.com/";
if([paramURLAsString length]==0)
{
NSLog(@"nil or empty is given!");
return;
}
NSURLCache * urlCache = [NSURLCache sharedURLCache];
/*设置缓存空间的大小--1M*/
[urlCache setMemoryCapacity:1*1024*1024];
/*创建一个nsurl*/
NSURL *url = [NSURL URLWithString:paramURLAsString];
/*创建一个请求*/
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];
/*从请求中获取缓存输出*/
NSCachedURLResponse *respose = [urlCache cachedResponseForRequest:request];
//判断是否有缓存
if(respose!=nil)
{
NSLog(@"如果有缓存输出,从缓存中获取数据");
//[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];//忽略缓存,重新下载
//[request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];//缓存中不存在才下载
//[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];//使用缓存,绝对不请求网络
//[request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];//忽略缓存,重新下载
//[request setCachePolicy:NSURLRequestReloadRevalidatingCacheData];//缓存于请求是否相同,同不下载,不同下载。
}
connection = nil;
NSURLConnection *newConnection = [[NSURLConnection alloc]initWithRequest:request delegate:selfstartImmediately:YES];
connection = newConnection;
}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
{
NSLog(@"即将发送请求.....");
return(request);
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"将接收输出.....");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"数据长度为 = %lu", (unsigned long)[data length]);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
//如果之前缓存中已经存在数据程序是不走这里的
NSLog(@"将缓存输出.....");
return(cachedResponse);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"请求完成.....");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"请求失败");
}