使用Photos来获取相册中所有图片
2016-11-15 15:25
225 查看
#import "AllPhotoViewController.h"
#import <Photos/Photos.h>
#import "ImageViewController.h"
@interface AllPhotoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *imageArr;
@property(nonatomic,strong)NSMutableArray <PHAsset*>
*assets;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,assign)CGSize size;
@property(nonatomic,strong)UIImagePickerController *imagePicker;
@end
@implementation AllPhotoViewController
- (void)viewDidLoad {
[super
viewDidLoad];
self.view.backgroundColor = [UIColor
whiteColor];
[self
createNav];
[self
createView];
[self
loadImage];
}
-(void)createNav{
UIFont *font;
CGRect frame;
if ([[UIDevice
currentDevice ]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
font = [UIFont
systemFontOfSize:11.0/375*ScreenWidth];
frame = CGRectMake(0, 0, 8.0/375*ScreenWidth, 15.0/375*ScreenWidth);
}else{
font = [UIFont
systemFontOfSize:16.0/375*ScreenWidth];
frame = CGRectMake(0, 0, 15.0/375*ScreenWidth, 25.0/375*ScreenWidth);
}
self.titleLabel= [MyTools
createLabelWithText:@"全部照片(0)"
andFont:font andTextAlignment:1
andTextColor:[UIColor
whiteColor]];
self.titleLabel.frame =
CGRectMake(0, 0, 100, 20);
self.navigationItem.titleView =
self.titleLabel ;
UIButton *back = [MyTools
createButtonWithFrame:frame
andBgImageName:@"scanback"];
[back addTarget:self
action:@selector(goBack)
forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem
alloc]initWithCustomView:back];
CGRect tframe;
if (IsPad) {
tframe = CGRectMake(0, 0, 18.0/375*ScreenWidth, 13.0/375*ScreenWidth);
}
else{
tframe = CGRectMake(0, 0, 25.0/375*ScreenWidth, 18.0/375*ScreenWidth);
}
UIButton *takePhoto = [MyTools
createButtonWithFrame:tframe
andBgImageName:@"zhaoxiangji"];
[takePhoto addTarget:self
action:@selector(goTake)
forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem
alloc]initWithCustomView:takePhoto];
}
-(void)goTake{
[self
presentViewController:self.imagePicker
animated:YES
completion:nil];
}
-(void)goBack{
[self.navigationController
popViewControllerAnimated:YES];
}
-(void)createView{
self.imageArr = [NSMutableArray
array];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout
alloc]init];
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
if ([[UIDevice
currentDevice]userInterfaceIdiom] ==
UIUserInterfaceIdiomPad) {
self.size =
CGSizeMake(50.0/375*ScreenWidth, 35.0/375*ScreenWidth);
}else{
self.size =
CGSizeMake(100.0/375*ScreenWidth, 70.0/375*ScreenWidth);
}
layout.itemSize =
self.size;
self.collectionView = [[UICollectionView
alloc]initWithFrame:CGRectMake(10.0/375*ScreenWidth, 10.0/375*ScreenWidth,
ScreenWidth - 20.0/375*ScreenWidth,
ScreenHeight) collectionViewLayout:layout];
self.collectionView.delegate =
self;
self.collectionView.dataSource =
self;
self.collectionView.backgroundColor = [UIColor
whiteColor];
self.collectionView.showsVerticalScrollIndicator =
NO;
[self.collectionView
registerClass:[UICollectionViewCell
class] forCellWithReuseIdentifier:@"cell"];
[self.view
addSubview:_collectionView];
}
//从相册获取图片
-(void)loadImage{
PHAuthorizationStatus status = [PHPhotoLibrary
authorizationStatus];
if (status ==
PHAuthorizationStatusRestricted ||
status == PHAuthorizationStatusDenied) {
[AlertView
alertWithTarget:self
andMessage:@"设置访问权限打开相册"
andConfirm:^(UIAlertAction *action) {
NSLog(@"点击了确定");
}];
}
self.assets = [self
getAllAssetInPhotoAblumWithAscending:YES];
_titleLabel.text = [NSString
stringWithFormat:@"全部图片(%ld)",_assets.count];
for (PHAsset *set
in _assets) {
PHImageRequestOptions *options = [[PHImageRequestOptions
alloc] init];
options.deliveryMode =
PHImageRequestOptionsDeliveryModeHighQualityFormat;
[[PHImageManager
defaultManager] requestImageForAsset:set
targetSize:[UIScreen
mainScreen].bounds.size
contentMode:PHImageContentModeAspectFit
options:options resultHandler:^(UIImage *result,
NSDictionary *info) {
//设置图片
[self.imageArr
addObject:result];
[self.collectionView
reloadData];
}];
//NSLog(@"%ld",_imageArr.count);
}
}
-(UIImagePickerController *)imagePicker{
if (_imagePicker ==
nil) {
_imagePicker = [[UIImagePickerController
alloc]init];
if ([UIImagePickerController
isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
_imagePicker .sourceType =
UIImagePickerControllerSourceTypeCamera;
//设置拍摄照片
_imagePicker.cameraCaptureMode =
UIImagePickerControllerCameraCaptureModePhoto;
_imagePicker.allowsEditing =
YES;
111a1
_imagePicker.delegate =
self;
} else {
[AlertView
alertWithTarget:self
andMessage:@"摄像头无法使用"
andConfirm:nil];
}
}
return
_imagePicker;
}
#pragma mark-- imagePicker的代理
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES
completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString
*,id> *)info{
//获取到图片
UIImage *image = [info
objectForKey:UIImagePickerControllerEditedImage];
//保存照片到相册
UIImageWriteToSavedPhotosAlbum(image,
self, @selector(image:didFinishSavingWithError:contextInfo:),
nil);
[picker dismissViewControllerAnimated:YES
completion:nil];
}
-(void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error) {
//error非nil保存失败
NSLog(@"%@
保存失败",[error
localizedDescription]);
}else
{
//保存成功
NSLog(@"保存成功");
[_imageArr
addObject:image];
[_collectionView
reloadData];
}
}
#pragma mark -- collection代理
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSLog(@"%ld",_imageArr.count);
return
_imageArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath
*)indexPath{
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"cell"
forIndexPath:indexPath];
UIImage *image =
_imageArr[indexPath.row];
//CGFloat height = image.size.height/image.size.width*100.0/375*ScreenWidth;
UIImageView *imageView = [[UIImageView
alloc]initWithFrame:cell.bounds];
imageView.image = image;
[cell.contentView
addSubview:imageView];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath
*)indexPath{
ImageViewController *imageV = [[ImageViewController
alloc]init];
[self.navigationController
pushViewController:imageV
animated:YES];
}
#pragma mark - 获取相册内所有照片资源
- (NSMutableArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending
{
NSMutableArray<PHAsset *> *assets = [NSMutableArray
array];
PHFetchOptions *option = [[PHFetchOptions
alloc] init];
//ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列
option.sortDescriptors = @[[NSSortDescriptor
sortDescriptorWithKey:@"creationDate"
ascending:ascending]];
PHFetchResult *result = [PHAsset
fetchAssetsWithMediaType:PHAssetMediaTypeImage
options:option];
[result enumerateObjectsUsingBlock:^(id
_Nonnull obj, NSUInteger idx,
BOOL * _Nonnull stop) {
PHAsset *asset = (PHAsset *)obj;
NSLog(@"照片名%@", [asset
valueForKey:@"filename"]);
[assets addObject:asset];
}];
// NSLog(@"%ld",assets.count);
return assets;
}
- (void)didReceiveMemoryWarning {
[super
didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
#import <Photos/Photos.h>
#import "ImageViewController.h"
@interface AllPhotoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *imageArr;
@property(nonatomic,strong)NSMutableArray <PHAsset*>
*assets;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,assign)CGSize size;
@property(nonatomic,strong)UIImagePickerController *imagePicker;
@end
@implementation AllPhotoViewController
- (void)viewDidLoad {
[super
viewDidLoad];
self.view.backgroundColor = [UIColor
whiteColor];
[self
createNav];
[self
createView];
[self
loadImage];
}
-(void)createNav{
UIFont *font;
CGRect frame;
if ([[UIDevice
currentDevice ]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
font = [UIFont
systemFontOfSize:11.0/375*ScreenWidth];
frame = CGRectMake(0, 0, 8.0/375*ScreenWidth, 15.0/375*ScreenWidth);
}else{
font = [UIFont
systemFontOfSize:16.0/375*ScreenWidth];
frame = CGRectMake(0, 0, 15.0/375*ScreenWidth, 25.0/375*ScreenWidth);
}
self.titleLabel= [MyTools
createLabelWithText:@"全部照片(0)"
andFont:font andTextAlignment:1
andTextColor:[UIColor
whiteColor]];
self.titleLabel.frame =
CGRectMake(0, 0, 100, 20);
self.navigationItem.titleView =
self.titleLabel ;
UIButton *back = [MyTools
createButtonWithFrame:frame
andBgImageName:@"scanback"];
[back addTarget:self
action:@selector(goBack)
forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem
alloc]initWithCustomView:back];
CGRect tframe;
if (IsPad) {
tframe = CGRectMake(0, 0, 18.0/375*ScreenWidth, 13.0/375*ScreenWidth);
}
else{
tframe = CGRectMake(0, 0, 25.0/375*ScreenWidth, 18.0/375*ScreenWidth);
}
UIButton *takePhoto = [MyTools
createButtonWithFrame:tframe
andBgImageName:@"zhaoxiangji"];
[takePhoto addTarget:self
action:@selector(goTake)
forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem
alloc]initWithCustomView:takePhoto];
}
-(void)goTake{
[self
presentViewController:self.imagePicker
animated:YES
completion:nil];
}
-(void)goBack{
[self.navigationController
popViewControllerAnimated:YES];
}
-(void)createView{
self.imageArr = [NSMutableArray
array];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout
alloc]init];
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
if ([[UIDevice
currentDevice]userInterfaceIdiom] ==
UIUserInterfaceIdiomPad) {
self.size =
CGSizeMake(50.0/375*ScreenWidth, 35.0/375*ScreenWidth);
}else{
self.size =
CGSizeMake(100.0/375*ScreenWidth, 70.0/375*ScreenWidth);
}
layout.itemSize =
self.size;
self.collectionView = [[UICollectionView
alloc]initWithFrame:CGRectMake(10.0/375*ScreenWidth, 10.0/375*ScreenWidth,
ScreenWidth - 20.0/375*ScreenWidth,
ScreenHeight) collectionViewLayout:layout];
self.collectionView.delegate =
self;
self.collectionView.dataSource =
self;
self.collectionView.backgroundColor = [UIColor
whiteColor];
self.collectionView.showsVerticalScrollIndicator =
NO;
[self.collectionView
registerClass:[UICollectionViewCell
class] forCellWithReuseIdentifier:@"cell"];
[self.view
addSubview:_collectionView];
}
//从相册获取图片
-(void)loadImage{
PHAuthorizationStatus status = [PHPhotoLibrary
authorizationStatus];
if (status ==
PHAuthorizationStatusRestricted ||
status == PHAuthorizationStatusDenied) {
[AlertView
alertWithTarget:self
andMessage:@"设置访问权限打开相册"
andConfirm:^(UIAlertAction *action) {
NSLog(@"点击了确定");
}];
}
self.assets = [self
getAllAssetInPhotoAblumWithAscending:YES];
_titleLabel.text = [NSString
stringWithFormat:@"全部图片(%ld)",_assets.count];
for (PHAsset *set
in _assets) {
PHImageRequestOptions *options = [[PHImageRequestOptions
alloc] init];
options.deliveryMode =
PHImageRequestOptionsDeliveryModeHighQualityFormat;
[[PHImageManager
defaultManager] requestImageForAsset:set
targetSize:[UIScreen
mainScreen].bounds.size
contentMode:PHImageContentModeAspectFit
options:options resultHandler:^(UIImage *result,
NSDictionary *info) {
//设置图片
[self.imageArr
addObject:result];
[self.collectionView
reloadData];
}];
//NSLog(@"%ld",_imageArr.count);
}
}
-(UIImagePickerController *)imagePicker{
if (_imagePicker ==
nil) {
_imagePicker = [[UIImagePickerController
alloc]init];
if ([UIImagePickerController
isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
_imagePicker .sourceType =
UIImagePickerControllerSourceTypeCamera;
//设置拍摄照片
_imagePicker.cameraCaptureMode =
UIImagePickerControllerCameraCaptureModePhoto;
_imagePicker.allowsEditing =
YES;
111a1
_imagePicker.delegate =
self;
} else {
[AlertView
alertWithTarget:self
andMessage:@"摄像头无法使用"
andConfirm:nil];
}
}
return
_imagePicker;
}
#pragma mark-- imagePicker的代理
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES
completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString
*,id> *)info{
//获取到图片
UIImage *image = [info
objectForKey:UIImagePickerControllerEditedImage];
//保存照片到相册
UIImageWriteToSavedPhotosAlbum(image,
self, @selector(image:didFinishSavingWithError:contextInfo:),
nil);
[picker dismissViewControllerAnimated:YES
completion:nil];
}
-(void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error) {
//error非nil保存失败
NSLog(@"%@
保存失败",[error
localizedDescription]);
}else
{
//保存成功
NSLog(@"保存成功");
[_imageArr
addObject:image];
[_collectionView
reloadData];
}
}
#pragma mark -- collection代理
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSLog(@"%ld",_imageArr.count);
return
_imageArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath
*)indexPath{
UICollectionViewCell *cell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"cell"
forIndexPath:indexPath];
UIImage *image =
_imageArr[indexPath.row];
//CGFloat height = image.size.height/image.size.width*100.0/375*ScreenWidth;
UIImageView *imageView = [[UIImageView
alloc]initWithFrame:cell.bounds];
imageView.image = image;
[cell.contentView
addSubview:imageView];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath
*)indexPath{
ImageViewController *imageV = [[ImageViewController
alloc]init];
[self.navigationController
pushViewController:imageV
animated:YES];
}
#pragma mark - 获取相册内所有照片资源
- (NSMutableArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending
{
NSMutableArray<PHAsset *> *assets = [NSMutableArray
array];
PHFetchOptions *option = [[PHFetchOptions
alloc] init];
//ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列
option.sortDescriptors = @[[NSSortDescriptor
sortDescriptorWithKey:@"creationDate"
ascending:ascending]];
PHFetchResult *result = [PHAsset
fetchAssetsWithMediaType:PHAssetMediaTypeImage
options:option];
[result enumerateObjectsUsingBlock:^(id
_Nonnull obj, NSUInteger idx,
BOOL * _Nonnull stop) {
PHAsset *asset = (PHAsset *)obj;
NSLog(@"照片名%@", [asset
valueForKey:@"filename"]);
[assets addObject:asset];
}];
// NSLog(@"%ld",assets.count);
return assets;
}
- (void)didReceiveMemoryWarning {
[super
didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
相关文章推荐
- 不使用UIImagePickerControllerOriginalImage获取相册图片
- 使用鼠标(像QQ截图一样)自由截取Unity程序中的任意地方 && 获取本地文件夹下的所有图片
- 获取IPhone相册中图片的方法(包括获取所有图片)
- iOS8下获取相册所有图片
- Swift - 使用ALAssetsLibrary获取相簿里所有图片,视频(附样例)
- 在Android中使用加载器(Loader)来实现获取本机中的所有图片,并进行查看图片的效果
- 获取IPhone相册中图片的方法(包括获取所有图片)
- 获取IPhone相册中图片的方法(包括获取所有图片)
- 不使用UIImagePickerControllerOriginalImage获取相册图片
- UI 13 SD的简单使用 &UIActionSheet_从相册获取图片
- 获取IPhone相册中图片的方法(包括获取所有图片)
- 选着图片后可以编辑图片和如何使用摄像机获取图片并保存相册
- 【Android】使用系统相机或者从相册中获取图片资源并进行适当裁剪
- 从android相册获取所有图片的路径
- Android使用加载器(Loader)实现获取本机中所有图片
- Android 获取系统相册中的所有图片
- 获取IPhone相册中图片的方法(包括获取所有图片)
- 使用ContentResolver获取手机所有图片及删除操作
- iOS8下获取相册所有图片
- 获取IPhone相册中图片的方法(包括获取所有图片)