Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a single image with ALAssetsLibrary

Allow me to preface this by saying this is my first time using the ALAssetsLibrary. I need to access the most recent photo in the user's saved photo gallery. It seems that to do this, I have to create an ALAssetsLibrary instance and iterate over every item in the user's gallery before selecting the last image. This is always worst-case scenario. Is there a faster/better way to approach this problem?

like image 230
Jacob Avatar asked Jun 13 '11 21:06

Jacob


2 Answers

You don't have to enumerate all the photos in the user's gallery. The ALAssetsGroup class has a method - (void)enumerateAssetsAtIndexes:(NSIndexSet *)indexSet options:(NSEnumerationOptions)options usingBlock:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock which you can use to indicate which assets you want to enumerate.

In your case it's only the last one so set indexSet to [NSIndexSet indexSetWithIndexesInRange:NSMakeRange([group numberOfAssets]-1, [group numberOfAssets]) where group is your ALAssetsGroup.

As @mithuntnt mentioned, you can get the ALAssetsGroup for the photo library using [[assetsLibrary] enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop)

like image 122
adriaan Avatar answered Oct 24 '22 23:10

adriaan


What about this:

[group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
    if (result) {
       *stop = YES;
       //...
    }
}];
like image 40
huoxinbird Avatar answered Oct 24 '22 22:10

huoxinbird