參考微信自定製相簿功能
需要選擇單張圖片,可以直接呼叫imagePickerViewController
但是往往我們需要同時上傳很多張
我們公司的系統要求是iOS8.0以上都支援,所以就基於AssetsLibrary自己做了一個
先氣看程式碼麻煩可以直接看我GitHub上的demo,編碼辛苦,覺得有用還望給個star以作鼓勵
效果如下
必須匯入
#import <AssetsLibrary/AssetsLibrary.h>
GFPhotoAlumController.m檔案
先遍歷所有相簿分組
//self.assetLib是一個可變陣列,將照片數大於0的ALAssetsGroup放進去
[self.assetLibenumerateGroupsWithTypes:ALAssetsGroupAllusingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
[group setAssetsFilter:[ALAssetsFilterallPhotos]];
if (group.numberOfAssets > 0) {
[self.assetGroupArrayaddObject:group];
}
}
if (self.assetGroupArray.count > 0) {
[self.tableViewreloadData];
}else{
//no photo
}
}
} failureBlock:^(NSError *error) {
NSLog(@"enumerateGroupsError:%@",error);
}];
在tableView的cell中顯示
UITableViewCell *cell = [tableView
ALAssetsGroup *group = self.assetGroupArray[indexPath.row];
cell.imageView.clipsToBounds = YES;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
cell.imageView.image = [UIImageimageWithCGImage:group.posterImage];
cell.textLabel.text = [NSStringstringWithFormat:@"%@ %@", [group valueForProperty:ALAssetsGroupPropertyName],[NSStringstringWithFormat:@"(%ld)", (long)group.numberOfAssets]];
return cell;
GFPhotosController.m檔案
由於系統ALAsset是沒有這個照片是否被選中狀態的,所以需要自己做一個
如下
@interface GFAsset : NSObject
@property(nonatomic)BOOL isSelected;
@property(nonatomic,strong)ALAsset *asset;
- (GFAsset *)initWithAsset:(ALAsset *)asset;
+ (GFAsset *)assetWithAsset:(ALAsset *)asset;
@end
選擇的group
遍歷Group,獲取GFAsset
[group enumerateAssetsWithOptions:NSEnumerationReverseusingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
[self.assetArrayaddObject:[GFAssetassetWithAsset:result]];
}else{
if (self.assetArray.count == 0) {
NSLog(@" no photo");
}
[self.collectionViewreloadData];
}
}];
將照片付給imageView
self.photoImgView.image = [UIImageimageWithCGImage:asset.asset.aspectRatioThumbnail];