仅获取包含至少一张照片

时间:2017-06-28 11:06:35

标签: ios swift photokit

在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)

但第一部分可以为我提供仅包含视频的专辑,这意味着在我将谓词应用到第二部分后,专辑将为空。在我开始使用它们之前,有没有办法在第一部分过滤掉这些专辑?

1 个答案:

答案 0 :(得分:2)

似乎在没有提取集合中的项目的情况下,不能像这样过滤集合。有关可用的提取选项,请参阅the docs; none允许按特定类型的媒体数量进行过滤。

我实现这一目标的方法是获取用户创建的所有相册,然后使用仅返回图像的谓词从相册中提取资源。

所以把它放在代码中:

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
}