Fetch only photos of type PHAssetMediaTypeImage form asset collection type PHAssetCollectionTypeSmartAlbum

帅比萌擦擦* 提交于 2019-12-09 08:05:24

问题


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.


回答1:


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.
        }
    }
}



回答2:


To do the same thing in swift :

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)


来源:https://stackoverflow.com/questions/28089378/fetch-only-photos-of-type-phassetmediatypeimage-form-asset-collection-type-phass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!