iOS學習筆記22—ASIHTTPRequest和ASIDownloadCache實現本機快取

來源:互聯網
上載者:User

 


         為了節約流量,同時也是為了更好的使用者體驗,目前很多應用都使用本機快取機制,其中以網易新聞的緩衝功能最為出色。我自己的應用也想加入本機快取的功能,於是我從網上查閱了相關的資料,發現總體上說有兩種方法。一種是自己寫緩衝的處理,一種是採用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"]];

 

ASIOnlyLoadIfNotCachedCachePolicy : / /如果緩衝的資料存在,則使用它,即使它是陳舊的。這意味著請求不會跟伺服器除非資源他們要求不是在緩衝中

[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這種儲存策略的快取資料,如果更換其他的參數的話,即可清理對應儲存策略的快取資料。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.