缓存网络请求的结果

显然在某些情况下我们很希望减少移动设备和网络的交互次数,这就需要使用iOS的内存缓存了。代码基本上没有什么需要解释的地方,注意不要乱缓存,注意根据需要清理缓存即可。

 1     //构建请求
 2     NSURL *url = [NSURL URLWithString:@"http://218.241.17.106/webService/configService.asmx/GetNewCarInfo?CarID=1"];
 3     NSURLCache *urlCache = [NSURLCache sharedURLCache];
 4     [urlCache setMemoryCapacity:1*1024*1024];
 5     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f];
 6     
 7     //如果有缓存,则从缓存中读取数据
 8     NSCachedURLResponse *response = [urlCache cachedResponseForRequest:request];
 9     if (response != nil){
10         [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
11     }
12     
13     //发送请求
14     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
15         NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
16         NSLog(@"%@", responseStr);
17     }];

代码基本没有什么需要解释的地方

posted @ 2014-07-12 15:57  肉排君  阅读(214)  评论(0编辑  收藏  举报