Skip to content

Instantly share code, notes, and snippets.

@ericcj
Created August 29, 2013 13:18
Show Gist options
  • Save ericcj/6377981 to your computer and use it in GitHub Desktop.
Save ericcj/6377981 to your computer and use it in GitHub Desktop.
enumerate camera roll in actual reverse chronological order
#import <AssetsLibrary/AssetsLibrary.h>
@interface ALAssetsGroup (TLEnumeration)
// assume camera roll is k-ordered by date
- (void)enumerateAssetsReverseKOrdered:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock;
@end
#import "ALAssetsGroup+TLEnumeration.h"
MAKE_CATEGORIES_LOADABLE(ALAssetsGroup_TLEnumeration)
@implementation ALAssetsGroup (TLEnumeration)
- (void)enumerateAssetsReverseKOrdered:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock
{
const NSUInteger k = 100;
__block NSUInteger bufferedIndex = 0;
__block BOOL bufferedStop = NO; // enumerateAssetsWithOptions can set stop so don't pass it directly
__block NSMutableArray *buffer = [NSMutableArray arrayWithCapacity:k];
[self enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
if (!asset || [buffer count] == k) {
[buffer sortUsingComparator:^NSComparisonResult(ALAsset *obj1, ALAsset *obj2) {
return [[obj2 valueForProperty:ALAssetPropertyDate] compare:[obj1 valueForProperty:ALAssetPropertyDate]];
}];
}
if (asset) {
if ([buffer count] == k) {
enumerationBlock(buffer[0], bufferedIndex++, &bufferedStop);
*stop = bufferedStop;
[buffer removeObjectAtIndex:0];
}
[buffer addObject:asset];
} else {
for (ALAsset *nextAsset in buffer) {
if (bufferedStop) break;
enumerationBlock(nextAsset, bufferedIndex++, &bufferedStop);
}
enumerationBlock(nil, index, stop); // pass original ending params through
}
}];
}
@end
@walsh2000
Copy link

Can I ask you about this code? Did you code this because you noticed that enumerateAssetsWithOptions would occasionally return assets out of order?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment