仅获取至少包含一张照片的 PHAssetCollections

Fetch only PHAssetCollections containing at least one photo

在 iOS PhotoKit 中,我可以像这样获取所有非空相册:

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")
let albumFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: albumFetchOptions)

albumFetchResult.enumerateObjects({ (collection, _, _) in
    // Do something with the album...
})

那么我只能从相册中获取这样的照片:

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetResourceType.photo.rawValue)
let fetchResults = PHAsset.fetchAssets(in: collection, options: fetchOptions)

但是第一部分可以给我只有视频的相册,这意味着我将谓词应用于第二部分后,相册将是空的。有没有办法在我开始使用它们之前过滤掉第一部分中的那些相册?

如果不同时获取集合中的项目,似乎无法像这样过滤集合。请参阅 the docs 了解可用的提取选项; none 允许按特定类型媒体的数量进行过滤。

我实现此目的的方法是获取用户创建的所有相册,然后使用 returns 仅图像的谓词从相册中获取资产。

因此将其放入代码中:

var userCollections: PHFetchResult<PHAssetCollection>!
// Fetching all PHAssetCollections with at least some media in it
let options = PHFetchOptions()
    options.predicate = NSPredicate(format: "estimatedAssetCount > 0")
// Performing the fetch
userCollections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: options)

接下来,通过指定谓词从图像集合中获取资产:

// Getting the specific collection (I assumed to use a tableView)
let collection = userCollections[indexPath.row]
let optionsToFilterImage = PHFetchOptions()
    optionsToFilterImage.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)
// Fetching the asset with the predicate to filter just images
let justImages = PHAsset.fetchAssets(in: collection, options: optionsToFilterImage)

最后,统计图片数量:

if justImages.count > 0 {
    // Display it
} else {
    // The album has no images
}