之前一直使用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];
}];
複製程式碼