您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發筆記 22:用 ASIHTTPRequest 與 ASIDownloadCache 做本地快取

編輯:iOS 開發綜合

為了省流量、也為了在網路不穩時還能看得到內容,很多 App 都會做本地快取。做法大致分兩種:自己寫一套快取邏輯,或直接用 ASIHTTPRequest 附的 ASIDownloadCache。想快速上手的話,第二條路成本低得多,效果其實也不差。

一、宣告全域的 Cache 物件

在 AppDelegate.h 裡多一個成員與屬性:

@interface AppDelegate : UIResponder <UIApplicationDelegate> {
    ASIDownloadCache *myCache;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) ASIDownloadCache *myCache;
@end

接著在 AppDelegate.m 的 didFinishLaunchingWithOptions 中建立並設定存放路徑與預設策略:

ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];
self.myCache = cache;
[cache release];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
[self.myCache setStoragePath:[documentDirectory stringByAppendingPathComponent:@"resource"]];

// 只要快取裡有資料就直接用,即使它已經過期
[self.myCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];

最後別忘了在 dealloc 釋放:

[myCache release];

二、在請求端套用快取

NSURL *url = [NSURL URLWithString:@"https://....../getPictureNews.aspx"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[request setDownloadCache:appDelegate.myCache];
// 永久保存到磁碟;若無更新或離線時就讀快取
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];

request.delegate = self;
[request startAsynchronous];

三、清理快取

把清空的動作放進 App 的「設定」頁,讓使用者自己決定何時清:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.myCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];

這裡清的是「永久保存」這一種策略的資料;換成其他參數,就能清對應策略的快取。

補充一句:ASIHTTPRequest 早已停止維護,新專案建議改用 NSURLSession 的 URLCache 或 SDWebImage、Alamofire 等成熟套件來取代上面這套寫法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved