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.

ChintaN -Maddy- Ramani
  • 5,006
  • 1
  • 24
  • 46
bhoomi
  • 363
  • 1
  • 4
  • 11

2 Answers2

29

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.
        }
    }
}
gabbler
  • 13,128
  • 4
  • 29
  • 41
  • 9
    @grabler it is throwing this error: `Unsupported predicate in fetch options: mediaType == 1` – Anish Kumar Feb 23 '16 at 23:18
  • 1
    @AnishKumar, doesn't happen to me, from [here](https://forums.developer.apple.com/thread/17498), similar issue on iOS 9.1, try upgrade to iOS 9.2. – gabbler Feb 24 '16 at 03:31
  • @AnishKumar @gabbler 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](https://developer.apple.com/documentation/photokit/phfetchoptions) you can see that `mediaType` is not supported for fetching `PHAssetCollections` only to fetch `PHAsset` – vander2675 Jul 29 '19 at 07:15
26

To do the same thing in swift :

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)
Max
  • 744
  • 7
  • 20