使用PhotosKit自定义多选相册

1,057 阅读2分钟

之前一直使用UIImagePickerController来做相片选择.新项目中要求多选,明显UIImagePickerController不支持.并且因为机器本身打开了icloud同步,本地只保存略缩图,研究之下发现苹果早已经给了一个新的框架.叫Photos.下面就是介绍使用photos来自定义多选相册的功能. 我也是受到其他博文的启发,原地址如下:

http://kayosite.com/ios-development-and-detail-of-photo-framework-part-two.html

官方demo

https://developer.apple.com/library/ios/samplecode/UsingPhotosFramework/Introduction/Intro.html

其实研究一下官方demo就可以了.已经写的很详细了.

建议先看kayo的文章. 我就先上代码了

//获取相册
//首先定义一个PHFetchResult
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
//从上文中得知PHFetchResult是一个相册的集合.可以使用遍历来获取
    for (int i=0; i<smartAlbums.count; i++) {
        PHCollection *collection = smartAlbums[i];
NSLog(@"%@",collection.localizedTitle) //输出的是相册的title. 你懂得 知道怎么利用.
    }
//获取相册内的照片
//首先定义一个PHCachingImageManager
    PHCachingImageManager* imageManager = [[PHCachingImageManager alloc] init];
    [imageManager stopCachingImagesForAllAssets];
    previousPreheatRect = CGRectZero;
        for (int i=0; i<smartAlbums.count; i++) {
            PHCollection *collection = smartAlbums[i];
PHAssetCollection* assetCollection=(PHAssetCollection*)collection;
PHFetchResult* fetchResult=[PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
for (int i=0; i<[fetchResult countOfAssetsWithMediaType:PHAssetMediaTypeImage]; i++) {
PHAsset* asset=fetchResult[i];
                  [imageManager requestImageForAsset:asset  targetSize:CGSizeMake(width, width)   contentMode:PHImageContentModeAspectFill  options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                 //这里回来的result就是略缩图. 会根据你的参数targetSize来返回的.
                             }];
    }

上面只取到略缩图.如何取得最大分辨率的照片呢?方法如下

//fetchResult取得方法和上个代码块中一样
    PHAsset* asset=fetchResult[count];
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.networkAccessAllowed = YES; //设置从网络获取
    options.progressHandler=^(double progress, NSError *error, BOOL *stop, NSDictionary *info){
//这是下载进度 值为progress
    };
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(1200,1200) contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
//result依旧是和上个代码块中一样. contentMode自己选.
        UIImageView* image=[[UIImageView alloc] initWithImage:result];
        image.frame=CGRectMake(0, 0, kScreenSize.width, kScreenSize.width);
        [self.contentView addSubview:image];
    }];