為了減少與服務器的連接溝通次數,提高應用程序的執行速度,使用了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(@"請求失敗");
}