获取本地相册并显示

本代码适用于iOS8,iOS9

#import "ViewController.h"

#import "ImageCell.h"

#import <Photos/Photos.h>

#import "UIView+Ext.h"


#define identifier @"image"


@interface ViewController () <UICollectionViewDataSource>


@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;


@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;


@property (nonatomic, strong) NSMutableArray *images;


@end


@implementation ViewController


- (NSMutableArray *)images {

    if (_images == nil) {

        _images = [NSMutableArray array];

    }

    return _images;

}


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    [self setupCollectionView];

    

    [self fetchImages];

}


- (void)setupCollectionView {

    [self.collectionView registerNib:[UINib nibWithNibName:@"ImageCell" bundle:nil] forCellWithReuseIdentifier:identifier];

    

    NSInteger n = 4;

    CGFloat margin = 1;

    CGFloat width = (ScreenW - margin * (n + 1)) / n;

    self.layout.itemSize = CGSizeMake(width, width);

    self.layout.sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin);

}


- (void)fetchImages {

    __weak typeof(self) weakSelf = self;

    

    PHImageManager *manager = [[PHImageManager alloc] init];

    

    PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAny options:nil];

    [assetCollections enumerateObjectsUsingBlock:^(PHAssetCollection *assetCollection, NSUInteger idx, BOOL * _Nonnull stop) {

        if ([assetCollection.localizedTitle isEqualToString:@"Camera Roll"]) {

            weakSelf.title = assetCollection.localizedTitle;

            

            PHFetchResult *assets = [PHAsset fetchKeyAssetsInAssetCollection:assetCollection options:nil];

            [assets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL * _Nonnull stop) {

                [manager requestImageForAsset:asset targetSize:self.layout.itemSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

                    [weakSelf.images addObject:result];

                    

                    if (idx == assets.count - 1) {

                        [weakSelf.collectionView reloadData];

                    }

                }];

            }];

        }

    }];

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.images.count;

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    cell.image = self.images[indexPath.row];

    return cell;

}


@end



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取本地相册的所有图片和视频以及它们的信息,你可以使用 `ContentResolver` 和 `Cursor`。下面是一个示例代码,演示如何获取本地相册中的所有图片和视频,并显示它们的信息: ```kotlin import android.content.ContentResolver import android.provider.MediaStore // 获取本地相册的所有图片和视频 fun getAllMediaFiles(contentResolver: ContentResolver) { val projection = arrayOf( MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.DISPLAY_NAME, MediaStore.Files.FileColumns.DATE_ADDED, MediaStore.Files.FileColumns.MIME_TYPE ) val selection = (MediaStore.Files.FileColumns.MEDIA_TYPE + "=" + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE + " OR " + MediaStore.Files.FileColumns.MEDIA_TYPE + "=" + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO) val sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC" val cursor = contentResolver.query( MediaStore.Files.getContentUri("external"), projection, selection, null, sortOrder ) cursor?.use { val idColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID) val nameColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME) val dateAddedColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_ADDED) val mimeTypeColumn = it.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE) while (it.moveToNext()) { val id = it.getLong(idColumn) val name = it.getString(nameColumn) val dateAdded = it.getLong(dateAddedColumn) val mimeType = it.getString(mimeTypeColumn) // 执行你的操作,例如显示图片或视频信息 println("ID: $id") println("Name: $name") println("Date Added: $dateAdded") println("MIME Type: $mimeType") println("---------------------") } } } // 在你的 Activity 或 Fragment 中调用该方法 fun getMediaFilesFromGallery() { val contentResolver = context?.contentResolver if (contentResolver != null) { getAllMediaFiles(contentResolver) } } ``` 在上面的代码中,`getAllMediaFiles()` 函数使用 `ContentResolver` 查询本地相册中的所有图片和视频。它指定了需要查询的列(ID、显示名称、添加日期和 MIME 类型),设置了查询条件(媒体类型为图片或视频),并按照添加日期降序排序。然后使用 `Cursor` 遍历查询结果,获取每个文件的信息,并执行相应操作,例如打印出文件的 ID、名称、添加日期和 MIME 类型。 你可以在你的 Activity 或 Fragment 中调用 `getMediaFilesFromGallery()` 方法来获取本地相册的所有图片和视频,并对它们进行操作。请注意确保你的应用有读取外部存储的权限。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值