Search code examples
iosobjective-cuicollectionviewuicollectionviewcellnsdocumentdirectory

how to load images faster from document directory in ios


I know there are so many answers related to my topic but not solved my problem.

my question is,

how can i load images faster into UICollectionView from document Directory .Present i am loading images perfectly into UICollectionView but images are loading very slowly.

My code is Below

Saving images into document Directory folder(Chandan)

UIImage *image = info[UIImagePickerControllerOriginalImage];


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = paths.firstObject;
NSData *imageData = UIImagePNGRepresentation(image);

NSString *imageFolder = @"Chandan";


NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMddHHmmss"];
NSDate *now = [NSDate date];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *myUniqueName = [NSString stringWithFormat:@"Photo-%@.png",theDate];

NSString *imagePath = [NSString stringWithFormat:@"%@/%@",documentDirectory,imageFolder];

BOOL isDir;
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:imagePath isDirectory:&isDir])
    if(![fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:NULL])
        NSLog(@"Error: folder creation failed %@", documentDirectory);

[[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@/%@", imagePath, myUniqueName] contents:nil attributes:nil];
[imageData writeToFile:[NSString stringWithFormat:@"%@/%@", imagePath, myUniqueName] atomically:YES];

And Loading Images from documentDirectory folder(Chandan) into array

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = paths.firstObject;
NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentDirectory, @"Chandan"]; // image path is same as above
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fullPath error:nil];

fileList=[[NSMutableArray alloc]init];
fileName=[[NSMutableArray alloc]init];

if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {

    for (NSString *filename in dirContents) {
        NSString *fileExt = [filename pathExtension];
        if ([fileExt isEqualToString:@"png"]) {
            NSString *fullPth = [fullPath stringByAppendingPathComponent:filename];
            [fileList addObject:fullPth];
            [fileName addObject:filename];
            NSLog(@"File name : %@ ",filename);
            NSLog(@"fullPth : %@ ",fullPth);

        }
    }


} else {

    NSLog(@"No Files");
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

return fileList.count;
 }

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

cell.imgView.image = nil;


NSString *filePath = [fileList objectAtIndex:indexPath.row];

 UIImage *image =[UIImage imageWithContentsOfFile:filePath];

//--asynchro--//

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{



    dispatch_async(dispatch_get_main_queue(), ^{
        if (image) {

             UIImage *imageToDisplay =[UIImage imageWithCGImage:[image CGImage]
                                             scale:1.0
                                       orientation: UIImageOrientationRight];

            cell.imgView.image = imageToDisplay;

          [activityIndicator stopAnimating];
           activityIndicator.hidden = YES;
           CollectionView.hidden = NO;


        } else {
            cell.imgView.image = [UIImage imageNamed:@"tours-walk.png"];
        }
    });
});


//--//   

cell.selectedLabel.backgroundColor = [UIColor clearColor];

// Configure the cell

cell.layer.shouldRasterize = true;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;


return cell;
 }

Any suggestions are very appreciated


Solution

  • Find the simple solution

    Changed this line

    NSData *imageData = UIImagePNGRepresentation(image);
    

    into

    NSData *imageData = UIImageJPEGRepresentation(image, 0.0);
    

    And also removed this line

    UIImage *imageToDisplay =[UIImage imageWithCGImage:[image CGImage]
                                             scale:1.0
                                       orientation: UIImageOrientationRight];