#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;
_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
本文档展示了如何使用Photos框架在iOS应用中获取相册中的所有图片,并在UICollectionView中展示。同时,提供了从相机拍照并保存到相册的功能。

4870

被折叠的 条评论
为什么被折叠?



