How can i access the photo from gallery using Photo framework in objective c

佐手、 提交于 2019-12-03 16:28:19

Add this in .h/.m file

#import <Photos/Photos.h>

Global variable :

@property(nonatomic , strong) PHFetchResult *assetsFetchResults;
@property(nonatomic , strong) PHCachingImageManager *imageManager;

viewDidLoad code :

// Fetch all assets, sorted by date created.
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
    _assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];

    _imageManager = [[PHCachingImageManager alloc] init];

numberOfItemsInSection method :

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_assetsFetchResults count];
}

UICollectionView cellForItemAtIndexPath: code :

UICollectionViewCell *cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];

UIImageView *imageView = (UIImageView *)[cell viewWithTag:101];
PHAsset *asset = _assetsFetchResults[indexPath.item];

        [_imageManager requestImageForAsset:asset targetSize:imageView.frame.size contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *result, NSDictionary *info)
         {
             imageView.image = result;
         }];

[EDITED]

Accessing the image:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PHAsset *asset = _assetsFetchResults[indexPath.item];

   [_imageManager requestImageForAsset:asset targetSize:CGSizeMake(200, 200) contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *result, NSDictionary *info)
         {
             // result is the actual image object.
         }];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!