Fetch only photos of type PHAssetMediaTypeImage form asset collection type PHAssetCollectionTypeSmartAlbum
Asked Answered
U

2

16

I am using the Photos framework to fetch album list in iOS8. I am able to do it using

PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

This gives me a list of all smart albums including videos. How can I filter out videos from this list. I need only images.

Help would be appreciated. Thanks.

Ubangi answered 22/1, 2015 at 12:58 Comment(0)
M
30

You should set up fetch options, its has a property predicate, which can be used to filter videos. Below is an example of doing that.

PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

//set up fetch options, mediaType is image.
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];

for (NSInteger i =0; i < smartAlbums.count; i++) {
    PHAssetCollection *assetCollection = smartAlbums[i];
    PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];

    NSLog(@"sub album title is %@, count is %ld", assetCollection.localizedTitle, assetsFetchResult.count);
    if (assetsFetchResult.count > 0) {
        for (PHAsset *asset in assetsFetchResult) {
            //you have got your image type asset.
        }
    }
}
Marten answered 22/1, 2015 at 13:38 Comment(3)
@grabler it is throwing this error: Unsupported predicate in fetch options: mediaType == 1Crinum
@AnishKumar, doesn't happen to me, from here, similar issue on iOS 9.1, try upgrade to iOS 9.2.Marten
@AnishKumar @Marten The Linked Thread from Developer Forums is about a predicate involving title not mediaType. I experienced this Error when trying to use this predicate on PHAssetCollection.fetchAssetCollectionsWithType(). From Developer documentation you can see that mediaType is not supported for fetching PHAssetCollections only to fetch PHAssetJelly
C
28

To do the same thing in swift :

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)
Cheddite answered 20/1, 2016 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.