Abh*_*nav 3 iphone cocoa nsurlconnection nsurlrequest
有没有人有使用NSURLRequest,NSURLConnection和NSURLRequestReturnCacheDataElseLoad策略实现图像缓存的示例代码?
我使用以下代码,但似乎没有发生缓存.我一直从URL获取图像.请告诉我这里有什么问题:
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://i54.tinypic.com/10pd2jk.png"]];
NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSLog(@"Received %d bytes", [data length]);
[req setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSLog(@"Received %d bytes", [data length]);
[[NSURLCache sharedURLCache] setMemoryCapacity:1024*1024*10];
UIImage *myImage = [UIImage imageWithData:data];
UIImageView *sd = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
sd.image = myImage;
[self.view addSubview:sd];
Run Code Online (Sandbox Code Playgroud)
您可能需要查看使用SDURLCache:https://github.com/rs/SDURLCache
SDURLCache实际上将缓存保存到磁盘,而NSURLCache则没有.NSURLCache仅在内存中缓存,因此在您的应用会话中.请参阅ReadMe链接,其中更详细地解释了它.
更新:从iOS 5.x开始,看起来NSURLCache会缓存到磁盘:http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/
| 归档时间: |
|
| 查看次数: |
2953 次 |
| 最近记录: |