天天看點

NSURLCache了解

iOS網絡請求中緩存技術用到了NSURLCache類,預設支援支援記憶體緩存和硬碟緩存。NSURLCache對NSURLRequest及其對應的NSCachedURLResponse緩存,并存放到本地資料庫中。(就是說隻要你使用NSURLRequest做網絡請求,系統預設使用NSURLCache幫你做緩存)

NSURLCache的常見方法

1)獲得全局緩存對象(沒必要手動建立)NSURLCache*cache = [NSURLCache sharedURLCache];

2)設定記憶體緩存的最大容量(位元組為機關,預設為512KB)- (void)setMemoryCapacity:(NSUInteger)memoryCapacity;

3)設定硬碟緩存的最大容量(位元組為機關,預設為10M)- (void)setDiskCapacity:(NSUInteger)diskCapacity;

4)硬碟緩存的位置:沙盒/Library/Caches

5)取得某個請求的緩存-(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;

6)清除某個請求的緩存-(void)removeCachedResponseForRequest:(NSURLRequest *)request;

7)清除所有的緩存-(void)removeAllCachedResponses;

代碼示範:

-(IBAction)post:(id)sender{

   NSURLCache *cache = [NSURLCache sharedURLCache];

   // 1.建立請求

   NSURL *url = [NSURLURLWithString:@"http://api1.zhimamei.com/appProductSearch"];

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

   NSCachedURLResponse *response = [cachecachedResponseForRequest:request];

   if (response) {

       NSLog(@"這個請求已經存在緩存");

       NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response.response;

        NSString *string =[httpResponse.allHeaderFields objectForKey:@"Date"];

       NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];

       [inputFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_CN"]];

       [inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];

       NSDate* inputDate = [inputFormatter dateFromString:string];

       NSDate *now = [NSDate date];

        //判斷緩存是否過期:超過兩小時

       if ([now timeIntervalSinceDate:inputDate] > 2 * 60 * 60  ) {

           NSURLCache *cache = [NSURLCache sharedURLCache];

           [cache removeCachedResponseForRequest:request];

           //設定緩存政策:忽略緩存,重新請求

           request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

       }else{

           //設定緩存政策:有緩存就用緩存,沒有緩存就不發請求,當做請求出錯處理(用于離線模式)

           request.cachePolicy = NSURLRequestReturnCacheDataDontLoad;

       }

    }else {

       NSLog(@"這個請求沒有緩存");

    }

   //發送請求

   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError*connectionError) {

       if (data) {

           NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableLeaves error:nil];

           NSLog(@"%@", dict);

       }

   }];

}