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

标签 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)

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

最佳答案

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

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

所以把它放在代码中:

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)

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

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

关于ios - 仅获取至少包含一张照片的 PHAssetCollections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44800729/

相关文章:

ios - Storyboard上具有动态高度的自定义 UIView

ios - 使用 Swift 在 UIBarButtonItem 上进行字距调整

java - 如何在 Android(Java) 中使用 json 反斜杠

ios - 玩家与物体碰撞时如何更改 View Controller ?

ios - PhotoKit:fetchAssetCollectionsWithLocalIdentifiers 失败

ios - 在 PhotoKit 中删除 : can you skip "Recently Deleted"?

iOS 和 Xcode : custom frameworks link error, undefined symbol

ios - 从 swift 3 转换为 swift 2.3 或从 iPhone 上的应用程序获取源代码

ios - 无法生成具有旧节数 : 1 and new section count: 0 with FetchedResultsController 的新节图

ios - PhotoKit - Swift 4 - 如何查找相同的照片或重复的照片 - PHFetchResult<PHAsset>