在IOS應(yīng)用程序開(kāi)發(fā)中,為了減少與服務(wù)端的交互次數(shù),加快用戶的響應(yīng)速度,一般都會(huì)在IOS設(shè)備中加一個(gè)緩存的機(jī)制。使用緩存的目的是為了使用的應(yīng)用程序能更快速的響應(yīng)用戶輸入,是程序高效的運(yùn)行。有時(shí)候我們需要將遠(yuǎn)程web服務(wù)器獲取的數(shù)據(jù)緩存起來(lái),減少對(duì)同一個(gè)url多次請(qǐng)求。下面將介紹如何在IOS設(shè)備中進(jìn)行緩存。
內(nèi)存緩存我們可以使用sdk中的NSURLCache類。NSURLRequest需要一個(gè)緩存參數(shù)來(lái)說(shuō)明它請(qǐng)求的url何如緩存數(shù)據(jù)的,我們先看下它的CachePolicy類型。
1、NSURLRequestUseProtocolCachePolicy NSURLRequest默認(rèn)的cache policy,使用Protocol協(xié)議定義。
2、NSURLRequestReloadIgnoringCacheData 忽略緩存直接從原始地址下載。
3、NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data時(shí)才從原始地址下載。
4、NSURLRequestReturnCacheDataDontLoad 只使用cache數(shù)據(jù),如果不存在cache,請(qǐng)求失敗;用于沒(méi)有建立網(wǎng)絡(luò)連接離線模式;
5、NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地和遠(yuǎn)程的緩存數(shù)據(jù),直接從原始地址下載,與NSURLRequestReloadIgnoringCacheData類似。
6、NSURLRequestReloadRevalidatingCacheData:驗(yàn)證本地?cái)?shù)據(jù)與遠(yuǎn)程數(shù)據(jù)是否相同,如果不同則下載遠(yuǎn)程數(shù)據(jù),否則使用本地?cái)?shù)據(jù)。
一些常用方法與屬性:
//獲取當(dāng)前應(yīng)用的緩存管理對(duì)象
+ (NSURLCache *)sharedURLCache;
//設(shè)置自定義的NSURLCache作為應(yīng)用緩存管理對(duì)象
+ (void)setSharedURLCache:(NSURLCache *)cache;
//初始化一個(gè)應(yīng)用緩存對(duì)象
/*
memoryCapacity 設(shè)置內(nèi)存緩存容量
diskCapacity 設(shè)置磁盤緩存容量
path 磁盤緩存路徑
內(nèi)容緩存會(huì)在應(yīng)用程序退出后 清空 磁盤緩存不會(huì)
*/
- (instancetype)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(nullable NSString *)path;
//獲取某一請(qǐng)求的緩存
- (nullable NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;
//給請(qǐng)求設(shè)置指定的緩存
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request;
//移除某個(gè)請(qǐng)求的緩存
- (void)removeCachedResponseForRequest:(NSURLRequest *)request;
//移除所有緩存數(shù)據(jù)
- (void)removeAllCachedResponses;
//移除某個(gè)時(shí)間起的緩存設(shè)置
- (void)removeCachedResponsesSinceDate:(NSDate *)date NS_AVAILABLE(10_10, 8_0);
//內(nèi)存緩存容量大小
@property NSUInteger memoryCapacity;
//磁盤緩存容量大小
@property NSUInteger diskCapacity;
//當(dāng)前已用內(nèi)存容量
@property (readonly) NSUInteger currentMemoryUsage;
//當(dāng)前已用磁盤容量
@property (readonly) NSUInteger currentDiskUsage;
簡(jiǎn)單例子:
#import
@interface ViewController : UIViewController
@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, nonatomic) NSURLCache *urlCache;
@property (strong, nonatomic) NSURL *url;
@property (strong, nonatomic) NSMutableURLRequest *request;
- (IBAction)reloadWebView:(UIButton *)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *paramURLAsString= @"http://blog.sina.com.cn/u/2526279194";
self.urlCache = [NSURLCache sharedURLCache];
[self.urlCache setMemoryCapacity:1*1024*1024];
//創(chuàng)建一個(gè)nsurl
self.url = [NSURL URLWithString:paramURLAsString];
//創(chuàng)建一個(gè)請(qǐng)求
self.request=[NSMutableURLRequest requestWithURL:self.url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0f];
[self.myWebView loadRequest:self.request];
}
這個(gè)例子中,我們請(qǐng)求url為http://blog.sina.com.cn/u/2526279194的網(wǎng)站。如果這個(gè)url被緩存了,我們直接從緩存中獲取數(shù)據(jù),否則從http://blog.sina.com.cn/u/2526279194站點(diǎn)上重新獲取數(shù)據(jù)。我們?cè)O(shè)置了緩存大小為1M。
- (IBAction)reloadWebView:(UIButton *)sender {
//從請(qǐng)求中獲取緩存輸出
NSCachedURLResponse *response =[self.urlCache cachedResponseForRequest:self.request];
//判斷是否有緩存
if (response != nil){
NSLog(@"如果有緩存輸出,從緩存中獲取數(shù)據(jù)");
[self.request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
[self.myWebView loadRequest:self.request];
self.connection = nil;
NSURLConnection *newConnection = [[NSURLConnection alloc] initWithRequest:self.request
delegate:self
startImmediately:YES];
self.connection = newConnection;
}
使用下面代碼,我將請(qǐng)求的過(guò)程打印出來(lái)
- (void) connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response{
NSLog(@"將接收輸出");
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse{
NSLog(@"即將發(fā)送請(qǐng)求");
return(request);
}
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data{
NSLog(@"接受數(shù)據(jù)");
NSLog(@"數(shù)據(jù)長(zhǎng)度為 = %lu", (unsigned long)[data length]);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse{
NSLog(@"將緩存輸出");
return(cachedResponse);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"請(qǐng)求完成");
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error{
NSLog(@"請(qǐng)求失敗");
}
@end
第一次打印結(jié)果如下
1
2
3
4
5
6
7
8
9
10
|
2013-01-31 15:28:29.923 NSURLCacheDemo[27848:907] 即將發(fā)送請(qǐng)求 2013-01-31 15:28:30.043 NSURLCacheDemo[27848:907] 將接收輸出 2013-01-31 15:28:30.045 NSURLCacheDemo[27848:907] 接受數(shù)據(jù) 2013-01-31 15:28:30.047 NSURLCacheDemo[27848:907] 數(shù)據(jù)長(zhǎng)度為 = 30047 2013-01-31 15:28:30.095 NSURLCacheDemo[27848:907] 接受數(shù)據(jù) 2013-01-31 15:28:30.098 NSURLCacheDemo[27848:907] 數(shù)據(jù)長(zhǎng)度為 = 3575 2013-01-31 15:28:30.102 NSURLCacheDemo[27848:907] 接受數(shù)據(jù) 2013-01-31 15:28:30.104 NSURLCacheDemo[27848:907] 數(shù)據(jù)長(zhǎng)度為 = 1482 2013-01-31 15:28:30.105 NSURLCacheDemo[27848:907] 將緩存輸出 2013-01-31 15:28:30.107 NSURLCacheDemo[27848:907] 請(qǐng)求完成 |
第二次點(diǎn)擊打印結(jié)果如下
1
2
3
4
5
6
|
2013-01-31 15:28:31.599 NSURLCacheDemo[27848:907] 如果有緩存輸出,從緩存中獲取數(shù)據(jù) 2013-01-31 15:28:31.607 NSURLCacheDemo[27848:907] 即將發(fā)送請(qǐng)求 2013-01-31 15:28:31.840 NSURLCacheDemo[27848:907] 將接收輸出 2013-01-31 15:28:31.843 NSURLCacheDemo[27848:907] 接受數(shù)據(jù) 2013-01-31 15:28:31.845 NSURLCacheDemo[27848:907] 數(shù)據(jù)長(zhǎng)度為 = 35104 2013-01-31 15:28:31.846 NSURLCacheDemo[27848:907] 請(qǐng)求完成 |
我們看到?jīng)]有“將緩存輸出”一項(xiàng),請(qǐng)求到的數(shù)據(jù)是第一次請(qǐng)求的累積,也就是第二次是從內(nèi)存中獲取數(shù)據(jù)的。