获取本地相册并显示

来源:互联网 发布:centos 安装gitlab 编辑:程序博客网 时间:2024/05/21 10:28

本代码适用于iOS8,iOS9

#import "ViewController.h"

#import "ImageCell.h"

#import <Photos/Photos.h>

#import "UIView+Ext.h"


#define identifier @"image"


@interface ViewController () <UICollectionViewDataSource>


@property (weak, nonatomic) IBOutletUICollectionViewFlowLayout *layout;


@property (weak, nonatomic) IBOutletUICollectionView *collectionView;


@property (nonatomic,strong) NSMutableArray *images;


@end


@implementation ViewController


- (NSMutableArray *)images {

    if (_images ==nil) {

        _images = [NSMutableArrayarray];

    }

    return_images;

}


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    [selfsetupCollectionView];

    

    [selffetchImages];

}


- (void)setupCollectionView {

    [self.collectionViewregisterNib:[UINibnibWithNibName:@"ImageCell"bundle:nil]forCellWithReuseIdentifier:identifier];

    

    NSInteger n = 4;

    CGFloat margin = 1;

    CGFloat width = (ScreenW - margin * (n +1)) / n;

    self.layout.itemSize =CGSizeMake(width, width);

    self.layout.sectionInset =UIEdgeInsetsMake(margin, margin, 0, margin);

}


- (void)fetchImages {

    __weak typeof(self) weakSelf =self;

    

    PHImageManager *manager = [[PHImageManageralloc] init];

    

    PHFetchResult *assetCollections = [PHAssetCollectionfetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbumsubtype:PHAssetCollectionSubtypeAnyoptions:nil];

    [assetCollections enumerateObjectsUsingBlock:^(PHAssetCollection *assetCollection,NSUInteger idx, BOOL *_Nonnull stop) {

        if ([assetCollection.localizedTitleisEqualToString:@"Camera Roll"]) {

            weakSelf.title = assetCollection.localizedTitle;

            

            PHFetchResult *assets = [PHAssetfetchKeyAssetsInAssetCollection:assetCollectionoptions:nil];

            [assets enumerateObjectsUsingBlock:^(PHAsset *asset,NSUInteger idx, BOOL *_Nonnull stop) {

                [manager requestImageForAsset:assettargetSize:self.layout.itemSizecontentMode:PHImageContentModeAspectFilloptions:nilresultHandler:^(UIImage *_Nullable result,NSDictionary *_Nullable info) {

                    [weakSelf.images addObject:result];

                    

                    if (idx == assets.count -1) {

                        [weakSelf.collectionViewreloadData];

                    }

                }];

            }];

        }

    }];

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.images.count;

}


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

    ImageCell *cell = [collectionViewdequeueReusableCellWithReuseIdentifier:identifierforIndexPath:indexPath];

    cell.image = self.images[indexPath.row];

    return cell;

}


@end



0 0
原创粉丝点击