iOS相册中图片按照时间排序

时间:2022-05-09 14:39:59

ios相册默认是按照时间从过去到现在排列,图片顺序有正序和逆序,group可以用以下方法来选择顺序

/**
@param NSIndexSet 需要获取的相册中图片范围
@param NSEnumerationOptions 获取图片的顺序(顺序还是逆序)
//ALAssetsGroupEnumerationResultsBlock的参数
@param result 照片ALAsset对象
@param index 当前result在该group相册中的位置,第index位置上
@param *stop 需要停止的时候 *stop = YES就停止继续运行当前相册group
*/
enumerateAssetsAtIndexes:(NSIndexSet *)indexSet options:(NSEnumerationOptions)options usingBlock:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock

示例如下

@property (nonatomic, strong) ALAssetsGroup *selectAssetsGroup;
-(void)loadAllPhotos{
NSInteger photoNumber = [self.selectAssetsGroup numberOfAssets];
NSIndexSet *IndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(, photoNumber)];
//图片按照逆序排列(由现在到过去)
[self.selectAssetsGroup enumerateAssetsAtIndexes:IndexSet options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
numberOfAssets++;
NSString *type = [result valueForProperty:ALAssetPropertyType];
if ([type isEqualToString:ALAssetTypePhoto]){
numberOfPhotos++;
}else if ([type isEqualToString:ALAssetTypeVideo]){
numberOfVideos++;
}
[assets addObject:result];
}
}];
}

若只想按照系统默认的顺序(由过去到现在),那么可以用

[self.selectAssetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
numberOfAssets++;
NSString *type = [result valueForProperty:ALAssetPropertyType];
if ([type isEqualToString:ALAssetTypePhoto]){
numberOfPhotos++;
}else if ([type isEqualToString:ALAssetTypeVideo]){
numberOfVideos++;
}
[assets addObject:result];
}
}];