Search code examples
iosobjective-cnsmutablearrayphotosframeworkphasset

Photos framework working abnormally.


I am using Photos framework to select photos from the Camera roll. After selecting the assets from the grid, I am using PHImageManager to access each of the selected images and then storing these images in array to show in a collection view of mine.

I am using this piece of code to achieve that:-

-(void)extractFullSizeImagesFromAssets{

    PHImageRequestOptions* options = [[PHImageRequestOptions alloc] init];
    options.version = PHImageRequestOptionsVersionCurrent;
    options.deliveryMode =  PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.networkAccessAllowed =  TRUE;



    for (int i = 0; i < self.assets.count; i++) {
        PHAsset * asset = [self.assets objectAtIndex:i];
        CGSize fullSizeImage = CGSizeMake(1000, (asset.pixelHeight / asset.pixelWidth) * 1000);


        [[PHImageManager defaultManager] requestImageForAsset:asset
                                   targetSize:fullSizeImage
                                  contentMode:PHImageContentModeAspectFit
                                      options:options
                                resultHandler:^(UIImage *image, NSDictionary *info){
                                   // [self.arr_images addObject:image];
                                    [_arr_fullSizeImages addObject:image];

        }];

    }
} 

Now my array "arr_fullSizeImages" contains the extracted images in some different random order than the way I did select while picking up the assets. For Example If I have selected 5 images from the camera roll then sometimes the selected image which was at index 3 in Camera Roll is saved on index 5 in the arr_fullSizeImages. I am not able to track the reason for this behaviour. Please identify the source of the mistake and how t solve this error also.

Thanks.


Solution

  • This is the expected behaviour as requestImageForAsset executed by default asynchronously. If you want a synchronous behaviour (and no random order), just set

    options.synchronous = YES;