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