Framework:AssetsLibrary.frameworkide
主要目的是獲取到系統相冊的數據,並把系統相冊裏的照片顯示出來。ui
一、建立一個新的項目;3d
二、將AssetsLibrary.framework添加到項目中。代理
三、打開故事板,拖放一個集合視圖(Collection View)組件到控制器中,而後拖放一個Image View到Collection View的默認單元格,在屬性面板中修改Image View的顯示照片方式爲Aspect Fill.而且,在屬性面板中設置默認單元格(collectionviewcell)的Identifier填入Cell;blog
四、將Collection View的數據源雨代理輸出口(outlet)鏈接到控制器(在Collection View上右鍵,鏈接就行,或者是在控制器的代碼裏手動設置也行)繼承
五、在項目中新增一個類,類名爲MyCell,而且繼承自uicollectionviewcell。it
六、在故事板裏,將collectionview單元格的類指向MyCell.io
七、將imageview與代碼關聯起來(就是連到MyCell中),命名爲imageView.table
八、在控制器代碼裏導入import
#import <AssetsLibrary/AssetsLibrary.h>
#import "MyCell.h"
而且讓此類符合
UICollectionViewDataSource,UICollectionViewDelegate協議的規範,而後聲明兩個變量
{
ALAssetsLibrary *library;
NSMutableArray *imageArr;
}
並將uicollectionview連接到代碼中。取名爲collView;
- (void)viewDidLoad {
[super viewDidLoad];
library = [[ALAssetsLibrary alloc]init];
// 使用參數取出全部存儲的文件照片
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
if (group != nil) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result != nil) {
[tempArray addObject:result];
}
}];
//保存結果
imageArr = [tempArray copy];
NSLog(@"取出照片共%lu張",(unsigned long)imageArr.count);
[self.collView reloadData];
}
} failureBlock:^(NSError *error) {
//讀取照片失敗
}];
}
#pragma markUICollectionViewDataSource UICollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return imageArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"cell";
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[MyCell alloc]init];
}
//取出每一張照片的數據並轉換成UIimage格式
CGImageRef img = [[imageArr objectAtIndex:indexPath.row] thumbnail];
cell.imageView.image = [UIImage imageWithCGImage:img];
return cell;
}