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

Framework:AssetsLibrary.framework

主要目的是获取到系统相册的数据,并把系统相册里的照片显示出来。

1、创建一个新的项目;

2、将AssetsLibrary.framework添加到项目中。

3、打开故事板,拖放一个集合视图(Collection View)组件到控制器中,然后拖放一个Image View到Collection View的默认单元格,在属性面板中修改Image View的显示照片方式为Aspect Fill.并且,在属性面板中设置默认单元格(collectionviewcell)的Identifier填入Cell;

4、将Collection View的数据源雨代理输出口(outlet)连接到控制器(在Collection View上右键,连接就行,或者是在控制器的代码里手动设置也行)

5、在项目中新增一个类,类名为MyCell,并且继承自uicollectionviewcell。

6、在故事板里,将collectionview单元格的类指向MyCell.

7、将imageview与代码关联起来(就是连到MyCell中),命名为imageView.

8、在控制器代码里导入

#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;

}

 

原文地址:https://www.cnblogs.com/mudy/p/4814460.html