iPhone開發筆記(16)使用ASIHTTPRequest和ASIDownloadCache實現本地緩存

    爲了節約流量,同時也是爲了更好的用戶體驗,目前很多應用都使用本地緩存機制,其中以網易新聞的緩存功能最爲出色。我自己的應用也想加入本地緩存的功能,於是我從網上查閱了相關的資料,發現總體上說有兩種方法。一種是自己寫緩存的處理,一種是採用ASIHTTPRequest中的ASIDownloadCache。根據我目前的技術水平和時間花費,我果斷選擇了後者,事實證明效果也很不錯。下面說一下實現方法:
    1、設置全局的Cache
    在AppDelegate.h中添加一個全局變量

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

   在AppDelegate.m中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加如下代碼

//自定義緩存
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];
    

    在AppDelegate.m中的dealloc方法中添加如下語句

[myCache release];

    到這裏爲止,就完成了全局變量的聲明。

    2、設置緩存策略

    在實現ASIHTTPRequest請求的地方設置request的存儲方式,代碼如下

NSString *str = @"http://....../getPictureNews.aspx";
NSURL *url = [NSURL URLWithString:str];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//獲取全局變量
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//設置緩存方式
[request setDownloadCache:appDelegate.myCache];
//設置緩存數據存儲策略,這裏採取的是如果無更新或無法聯網就讀取緩存數據
[request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
request.delegate = self;
[request startAsynchronous];

    3、清理緩存數據

    我在這裏採用的是手動清理數據的方式,在適當的地方添加如下代碼,我將清理緩存放在了應用的設置模塊:

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


    這裏清理的是ASICachePermanentlyCacheStoragePolicy這種存儲策略的緩存數據,如果更換其他的參數的話,即可清理對應存儲策略的緩存數據。


    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章