实现 NSURLRequest、NSURLConnection 和 NSURLRequestReturnCacheDataElseLoad 策略
有人有使用 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];
Do anyone have a sample code for implementing image caching using NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy?
I am using the following code but seems like no caching is happening. All the time I am getting the image from the URL. Please tell me what's wrong here:
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想看看如何使用 SDURLCache: https://github.com/rs/SDURLCache
SDURLCache实际上将缓存保存到磁盘,而 NSURLCache 则不然。 NSURLCache 仅缓存在内存中,因此在您的应用程序会话中。请参阅链接中的自述文件,其中有更详细的解释。
更新: 看起来 NSURLCache 从 iOS 5.x 开始就缓存到磁盘:http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/
You may want to take a look at using SDURLCache: https://github.com/rs/SDURLCache
SDURLCache actually saves cache to disk, whereas NSURLCache doesn't. NSURLCache only caches in memory, so within your app session. See ReadMe at link which explains it in more detail.
Update: Looks like NSURLCache does cache to disk since iOS 5.x: http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/
或者尝试 https://github.com/rs/SDWebImage
Or try https://github.com/rs/SDWebImage