实现 NSURLRequest、NSURLConnection 和 NSURLRequestReturnCacheDataElseLoad 策略

发布于 2024-10-14 02:46:42 字数 902 浏览 5 评论 0原文

有人有使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清风无影 2024-10-21 02:46:42

您可能想看看如何使用 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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文