UITableView和UICollectionView

相册列表

2022-08-17  本文已影响0人  失忆的程序员

简单写个相册列表,自行扩展

权限设置别忘记了,在info中添加。【隐私访问】

super dev.jpg

.h
自己加个传选中的值

.m

// 

#import "SelectPhotosViewController.h"
#import "PhotoCollectionViewCell.h"
#import <Masonry.h>
#import <Photos/Photos.h>

#define KHeaterCollectionViewCellWidth(section) (kScreenWidth - (section-1+2)*kFitWidth(10))/(section)
#define kScreenWidth [UIScreen  mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kFitHeight(height) (height)/(667.0 - 64) * (kScreenHeight - 64)
#define kFitWidth(width) (width)/375.0 * kScreenWidth
#define KModelCollectionViewCellIdentifier @"modelCollectionViewCellIdentifier"

@interface SelectPhotosViewController ()
<
UICollectionViewDelegate, UICollectionViewDataSource
>

@property (nonatomic, strong) UICollectionView *showPhotoCollectionView;
@property (nonatomic, strong) NSMutableArray *photoArray;

@end

@implementation SelectPhotosViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.photoArray = @[].mutableCopy;
    [self initNav];
    if (!_showPhotoCollectionView) {
        [self.view addSubview:self.showPhotoCollectionView];
    }
    //[self getOriginalImages];
    [self enumerateAssetsInAssetCollection:nil original:NO imageAndVideo:NO];
    //[self enumerateAssetsInAssetCollection:nil original:NO imageAndVideo:YES];
}

- (void)initNav
{
    // 在主线程异步加载,使下面的方法最后执行,防止其他的控件挡住了导航栏
    dispatch_async(dispatch_get_main_queue(), ^{
        // 隐藏系统导航栏
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        // 创建假的导航栏
        UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)];
        navView.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.0f];
        [self.view addSubview:navView];
        // 创建导航栏左按钮
        UIButton *left= [UIButton buttonWithType:UIButtonTypeSystem];
        left.frame = CGRectMake(20, 27, 30, 30);
        [left setBackgroundImage:[UIImage imageNamed:@"Numberback_highlight"] forState:UIControlStateNormal];
        [left addTarget:self action:@selector(preAction) forControlEvents:UIControlEventTouchUpInside];
        [navView addSubview:left];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLabel.text = @"添加智能图标";
        titleLabel.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0f];
        titleLabel.frame = CGRectMake(left.frame.origin.x + left.frame.size.width + 20, 20, 150, 44);
        [navView addSubview:titleLabel];
    });
}

-(void)preAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

// MARK: -----

//- (void)getOriginalImages
//{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        // 获得所有的自定义相簿
//        PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
////        // 遍历所有的自定义相簿
////        for (PHAssetCollection *assetCollection in assetCollections) {
////            [self enumerateAssetsInAssetCollection:assetCollection original:YES];
////        }
//
//        // 获得相机胶卷
//        PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
//        // 遍历相机胶卷,获取大图
//        [self enumerateAssetsInAssetCollection:cameraRoll original:YES];
//    });
//}
//
//- (void)getThumbnailImages
//{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        // 获得所有的自定义相簿
//        PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
//        // 遍历所有的自定义相簿
//        for (PHAssetCollection *assetCollection in assetCollections) {
//            [self enumerateAssetsInAssetCollection:assetCollection original:NO];
//        }
//        // 获得相机胶卷
//        PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
//        [self enumerateAssetsInAssetCollection:cameraRoll original:NO];
//    });
//}

/**
 *  遍历相簿中的全部图片
 *  @param assetCollection 相簿
 *  @param original        是否要原图
 */
//- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original
//{
//    NSLog(@"相簿名:%@", assetCollection.localizedTitle);
//    __weak typeof(self) weakSelf = self;
//
//    // 列出所有相册智能相册
//    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
//    // 列出所有用户创建的相册
//    PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
//    // 获取所有资源的集合,并按资源的创建时间排序
//    PHFetchOptions *options = [[PHFetchOptions alloc] init];
//    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
//    PHFetchResult *assets = [PHAsset fetchAssetsWithOptions:options];
//
//    PHImageManager *imageManager = [[PHImageManager alloc] init];
//
//    for (int i = 0; i < assets.count; i++)
//    {
//        PHAsset *asset = assets[i];//[assets lastObject];
//
//        switch (asset.mediaType) {
//            case PHAssetMediaTypeUnknown: {
//
//            } break;
//            case PHAssetMediaTypeImage: {
//
//                // 是否要原图
//                CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
//
//                // 从asset中获得图片
//                [imageManager requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//                    NSLog(@"%@", result);
//                    if (result) {
//                        original ? [weakSelf.photoArray addObject:result] : [weakSelf.photoArray addObject:result];
//                    } else {
//                        NSLog(@" ----------- ");
//                    }
//                }];
//                dispatch_async(dispatch_get_main_queue(), ^{
//
//                    [weakSelf.showPhotoCollectionView reloadData];
//                    weakSelf.showPhotoCollectionView.hidden = NO;
//                    [weakSelf scrollPositionBottom];
//                });
//            } break;
//            case PHAssetMediaTypeVideo: {
//
//            } break;
//            case PHAssetMediaTypeAudio: {
//
//            } break;
//
//            default:
//                break;
//        }
//    }
//
//}




/**
 *  遍历相簿中的全部图片
 *  @param assetCollection 相簿
 *  @param original        是否要原图
 */
- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original imageAndVideo:(BOOL)imageAndVideo
{
    NSLog(@"相簿名:%@", assetCollection.localizedTitle);
    __weak typeof(self) weakSelf = self;
    
    // 列出所有相册智能相册
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    // 列出所有用户创建的相册
    PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
    
    //PHImageManager *imageManager = [[PHImageManager alloc] init];
    PHImageManager *imageManager = [PHImageManager defaultManager];
    // 获取所有资源的集合,并按资源的创建时间排序
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    PHFetchResult *assets = [PHAsset fetchAssetsWithOptions:options];
    
    for (int i = 0; i < assets.count; i++)
    {
        PHAsset *phasset = assets[i];//[assets lastObject];
        // 是否要原图
        CGSize size = original ? CGSizeMake(phasset.pixelWidth, phasset.pixelHeight) : CGSizeZero;
        
        if (imageAndVideo)
        {
            switch (phasset.mediaType) {
                case PHAssetMediaTypeUnknown: {
                    
                } break;
                case PHAssetMediaTypeImage: {
                    
                    PHImageRequestOptions *roptions = [[PHImageRequestOptions alloc] init];
                    roptions.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
                    roptions.networkAccessAllowed = YES; // 网络的
                    // 从asset中获得图片
                    [imageManager requestImageForAsset:phasset targetSize:size contentMode:PHImageContentModeDefault options:roptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                        NSLog(@"%@", result);
                        if (result) {
                            original ? [weakSelf.photoArray addObject:result] : [weakSelf.photoArray addObject:result];
                        } else {
                            NSLog(@" ----------- ");
                        }
                    }];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [weakSelf.showPhotoCollectionView reloadData];
                        weakSelf.showPhotoCollectionView.hidden = NO;
                        [weakSelf scrollPositionBottom];
                    });
                } break;
                case PHAssetMediaTypeVideo: {
                    
                } break;
                case PHAssetMediaTypeAudio: {
                    
                } break;
                    
                default:
                    break;
            }
        }
        else
        {
            switch (phasset.mediaType) {
                case PHAssetMediaTypeUnknown: {
//                    NSLog(@" -------- PHAssetMediaTypeUnknown ");
                } break;
                case PHAssetMediaTypeImage: {
//                    NSLog(@" -------- PHAssetMediaTypeImage ");
                } break;
                case PHAssetMediaTypeVideo: {
//                    NSLog(@" -------- PHAssetMediaTypeVideo ");
                    
                    PHVideoRequestOptions *roptions = [[PHVideoRequestOptions alloc] init];
                    roptions.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
                    roptions.networkAccessAllowed = YES; // 网络的
                    
                    [imageManager requestAVAssetForVideo:phasset options:roptions resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                        AVURLAsset *urlAsset = (AVURLAsset *)asset;
                        NSURL *url = urlAsset.URL;
                        //NSData *data = [NSData dataWithContentsOfURL:url];
                        NSLog(@"-----------data url -> %@", url);
                        if (urlAsset) {
                            CMTime time = [asset duration];
                            AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
                            generator.appliesPreferredTrackTransform = YES;
                            // 总帧数/展示的总数量
                            long long baseCount = time.value / time.timescale;
                            // 取出PHOTP_COUNT张图片,存放到数组,用于collectionview
                            //for (NSInteger i = 0; i < 1; i++)
                            //{ // 每隔baseCount帧取一帧存起来,一共
                            //}
                            
                            NSError *error = nil;
                            // 每隔baseCount帧取一帧存起来,一共 ? 张, 当前获取第0张
                            CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, time.timescale) actualTime:NULL error:&error];
                            {
                                UIImage *image = [UIImage imageWithCGImage:img];
                                [weakSelf.photoArray addObject:image];
                                NSLog(@" ----------------- 封面 image -> %@, 时长: %lld ", image, baseCount);
                            }
                            
                        } else {
                            NSLog(@" ------------------> 走丢了!!! ");
                        }

                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            [weakSelf.showPhotoCollectionView reloadData];
                            weakSelf.showPhotoCollectionView.hidden = NO;
                            [weakSelf scrollPositionBottom];
                        });
                    }];
                    
                } break;
                case PHAssetMediaTypeAudio: {
                    NSLog(@" -------- PHAssetMediaTypeAudio ");
                    
                } break;
                    
                default:
                    break;
            }
        }
    }
    
}

#pragma mark  - 滑到最底部
- (void)scrollPositionBottom
{
    NSInteger section = [self.showPhotoCollectionView numberOfSections];  //有多少组
    if (section<1) return;  //无数据时不执行 要不会crash
    NSInteger row = [self.showPhotoCollectionView numberOfItemsInSection:section-1]; //最后一组有多少行
    if (row<1) return;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row-1 inSection:section-1];  //取最后一行数据
    [self.showPhotoCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];//滚动到最后一行
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UICollectionView *)showPhotoCollectionView
{
    if (!_showPhotoCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(KHeaterCollectionViewCellWidth(4.0), KHeaterCollectionViewCellWidth(4.0));
        _showPhotoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) collectionViewLayout:flowLayout];
        _showPhotoCollectionView.backgroundColor = [UIColor whiteColor];
        _showPhotoCollectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
        _showPhotoCollectionView.delegate = self;
        _showPhotoCollectionView.dataSource = self;
        _showPhotoCollectionView.allowsSelection = YES;
        [_showPhotoCollectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:KModelCollectionViewCellIdentifier];
        _showPhotoCollectionView.hidden = YES;
    }
    return _showPhotoCollectionView;
}

#pragma mark --- UICollectionViewDelegate && UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _photoArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
//    * 自行创建 cell ,显示图片,扩展去吧
    
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KModelCollectionViewCellIdentifier forIndexPath:indexPath];
    cell.iconImageView.image = _photoArray[indexPath.item];
    cell.iconlb.text = [NSString stringWithFormat:@"第%ld张", (indexPath.row + 1)];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    if (_photoArray[indexPath.item]) {
//        self.selectPhoto(_photoArray[indexPath.item]);
//    }
    
//    [self.navigationController popViewControllerAnimated:YES];
}








@end


想什么呢点赞啊!

jio.gif
上一篇 下一篇

猜你喜欢

热点阅读