iOS 获取系统相册数据(不是调系统的相册)

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;

}

 

相关文章
相关标签/搜索