Pankaj Pankaj - 1 year ago 144
Objective-C Question

IOS Photo Library fetch album name for a given photo

I've been looking everywhere but have not been able to find an answer to this.

In IOS PhotosFramework how I take an image/PHAsset and find out what all collections/albums it is assigned to ?

I already know how to get a list of all the albums from there I can also get all images inside each album. But how do I do it the other way around - i.e. for a given PHAsset how to get the name of Album/Collections that are assigned to it.

Here is the code I have to get a list of all albums in Camera Roll:

-(void) listAllAlbums{

PHFetchOptions *userAlbumsOptions = [PHFetchOptions new];
userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"];

PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:userAlbumsOptions];

NSLog(@"--------- entered %s ------------- ", __PRETTY_FUNCTION__);

[userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
NSLog(@"album title %@", collection.localizedTitle);

NSLog(@"--------- end of %s ------------- ", __PRETTY_FUNCTION__);



Answer Source

To paraphrase old Apple commercials... there's an API for that.

If you have a PHAsset, you can get the set of albums containing it with fetchAssetCollectionsContainingAsset:withType:options:. If you want just user-created albums, pass PHAssetCollectionTypeAlbum for the type parameter; if you also want smart albums (like the Camera Roll, or the other automatically collected albums such as Panoramas or Screenshots), call it again and pass PHAssetCollectionTypeSmartAlbum.

After calling that, you can enumerate through the results and read the localizedTitle of each. (By the way, PHFetchResult supports NSFastEnumeration, so you don't have to use enumerateObjectsUsingBlock unless you want to for some reason... you can just use a for-in loop.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download