Need to save and retrieve UIImages using a buffer

My application is a kind of picture gallery. when the user clicks on the icon in the gallery, he needs to display images (landscape images 2, portrait 1 image). Images can be more than 100. I usually take a raw file and decode in UIImage format. If the user wants to see another image, it takes some time (delay) to display the image due to decoding. So I want to save some images in cache (NSArray) in a separate stream (GCD) to solve this problem.

In the array I can store from 5 to 10 images. It is necessary to update every time the user skips.

Please give suggestions.

Thanks in advance.

+6
source share
3 answers

try this option -

UIImage *image = [imageCache objectForKey:@"myImage"]; if (!image) { // download image dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:yourURL]]; if (imageData) { // Set image to cache [imageCache setObject: [UIImage imageWithData:imageData] forKey:@"myImage"]; dispatch_async(dispatch_get_main_queue(), ^{ [yourImageView setImage:[UIImage imageWithData:imageData]]; }); } }); } else { // Use image from cache [yourImageView setImage:image]; } 
+2
source

I implemented NSCache using GCD

 dispatch_async(dispatch_get_global_queue(0, 0), ^{ [self storeInCache]; dispatch_async(dispatch_get_main_queue(), ^{ UIImage *image=[_imageCache objectForKey:@"P5"]; self.imageView = [[UIImageView alloc] initWithImage:image]; self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image.size}; [self.scrollView addSubview:self.imageView]; self.scrollView.contentSize = image.size; }); }); 

// Store 5 images in NSCache

 -(void)storeInCache { UIImage *image = [UIImage imageNamed:@"photo1.png"]; [_imageCache setObject:image forKey:@"P1"]; UIImage *image2 = [UIImage imageNamed:@"photo2.png"]; [_imageCache setObject:image2 forKey:@"P2"]; UIImage *image3 = [UIImage imageNamed:@"photo3.png"]; [_imageCache setObject:image3 forKey:@"P3"]; UIImage *image4 = [UIImage imageNamed:@"photo4.png"]; [_imageCache setObject:image4 forKey:@"P4"]; UIImage *image5 = [UIImage imageNamed:@"photo5.png"]; [_imageCache setObject:image5 forKey:@"P5"]; 

}

+3
source

You can use Apple's LazyTableImages .

This code will download the image in the background and set to view the images when the download is complete. You can add a placeholder image until your original image is uploaded.

I have used this sample in many applications, so I can also help you with the implementation if you need to.

Hope this helps you.

0
source

Source: https://habr.com/ru/post/984836/


All Articles