开发者

Implementing NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy

开发者 https://www.devze.com 2023-02-05 20:53 出处:网络
Do anyone have a sample code for implementing image caching using NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy?

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 = myImag开发者_开发百科e;
    [self.view addSubview:sd];


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/


Or try https://github.com/rs/SDWebImage

0

精彩评论

暂无评论...
验证码 换一张
取 消