其實Nsurlcache本身就有磁盤緩存的功能,但是在iOS上,NSCachedURLResponse僅限於不緩存到磁盤(NSURLCacheStorageAllowed視為NSURLCache存儲允許)。
但既然知道了原理,我們只需要自己實現NSURLCache的壹個子類,然後重新編寫cachedResponseForRequest:方法從硬盤讀取緩存即可。
讓我們開始工作。這個演示邏輯很復雜,所以我會壹步壹步地解釋。
首先定義視圖和控制器。
其邏輯是在打開應用時嘗試訪問緩存的文件,如果存在,則顯示緩存完畢;否則,嘗試下載整個網頁的資源;下載完成後,還會顯示緩存。
但是,下載所有資源都需要解析HTML,甚至JavaScript和CSS。為了簡化,我只是用壹個不顯示的UIWebView加載這個頁面,讓它自動發起所有請求。
當然,緩存之後,需要觸發壹個事件來顯示網頁。然後提供另壹個按鈕,單擊它顯示緩存的網頁,再次單擊它關閉它。
對了,本來想以Google為例,可惜它自己實現了HTML 5的離線瀏覽,無法體現這種方式的意義,只好拿百度當坐墊了。
目標-c代碼集合代碼
#導入& ltui kit/ui kit . h & gt;
@ interface webview controller:uiview controller & lt;UIWebViewDelegate & gt{
UIWebView * web
UILabel *標簽;
}
@property (nonatomic,retain)ui webview * web;
@property (nonatomic,retain)ui label * label;
-(I action)點擊;
@end
#導入" WebViewController.h "
#導入" URLCache.h "
@實現WebViewController
@合成web,標簽;
-(I action)單擊{
if (web) {
[web removeFromSuperview];
self.web = nil
}否則{
CGRect frame = {{0,0},{320,380 } };
ui webview * webview =[[ui webview alloc]initWithFrame:frame];
webview.scalesPageToFit = YES
self.web = webview
NSURLRequest * request =[nsurlrequestwithrul:[nsurlretwithring:@ "/"]];
[webview load request:request];
【self . view addSubview:webview】;
【webview發布】;
}
}
- (void)添加按鈕{
CGRect frame = {{130,400},{60,30 } };
ui button * button =[ui button button with type:uibuttontypearounderect];
button.frame = frame
[button add target:self action:@ selector(click)for control events:UIControlEventTouchUpInside];
[按鈕結算:@ "我點擊" for state:uicontrollestatenormal];
[self . view addSubview:button];
}
- (void)viewDidLoad {
【超級viewDidLoad】;
URL cache * shared cache =[[URL cache alloc]initWithMemoryCapacity:1024 * 1024 disk capacity:0 disk path:nil];
[NSURLCache setSharedURLCache:shared cache];
CGRect frame = {{60,200},{200,30 } };
ui label * text label =[[ui label alloc]initWithFrame:frame];
text label . text alignment = UITextAlignmentCenter;
[self . view add subview:text label];
self.label = textLabel
如果(![shared cache . responsesinfo count]){//未緩存
TextLabel.text = @ "在緩存中…";
CGRect frame = {{0,0},{320,380 } };
ui webview * webview =[[ui webview alloc]initWithFrame:frame];
webview.delegate = self
self.web = webview
NSURLRequest * request =[nsurlrequestwithrul:[nsurlretwithring:@ "/"]];
[webview load request:request];
【webview發布】;
}否則{
TextLabel.text = @ "已從硬盤讀取緩存";
[自行添加按鈕];
}
[sharedCache發布];
}
-(void)webView:(ui webView *)webView didFailLoadWithError:(NSError *)錯誤{
self.web = nil
Label.text = @ "請在運行此應用程序之前連接到網絡";
}
-(void)webViewDidFinishLoad:(ui webView *)webView {
self.web = nil
Label.text = @ "緩存完成";
[自行添加按鈕];
URL cache * shared cache =(URL cache *)[NSURLCache sharedURLCache];
[shared cache save info];
}
-(void)didReceiveMemoryWarning {
【超級didReceiveMemoryWarning】;
如果(!web) {
URL cache * shared cache =(URL cache *)[NSURLCache sharedURLCache];
[shared cache removeAllCachedResponses];
}
}
- (void)viewDidUnload {
self.web = nil
self.label = nil
}
- (void)dealloc {
【超級dealloc】;
【網絡發布】;
【標簽發布】;
}
@end