Swift Fetching smartAlbum with 至少一个媒体



我正在获取用户库中存在的所有智能相册。我使用的代码是这样的:

 var smartAlbums: PHFetchResult<PHAssetCollection>!
override func viewDidLoad() {
    super.viewDidLoad()
let options = PHFetchOptions()
    options.predicate = NSPredicate(format: "estimatedAssetCount > 0")
    options.sortDescriptors = [NSSortDescriptor(key: "localizedTitle", ascending: true)]
    smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: options)

i将在表格视图中显示结果,我用它来计算部分中的行数:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch Section(rawValue: section)! {
    case .allPhotos: return 1
    case .smartAlbums: return smartAlbums.count
    case .userCollections: return userCollections.count
    }
}

一切正常...但智能相册的获取结果也会获取零媒体的专辑。基本上它获取所有专辑。似乎没有考虑谓词。 相同的谓词应用于用户集合,并且工作正常。

 userCollections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: options) // this works fine

有没有办法只获取至少一个媒体的智能相册?

谢谢!

这就是我解决它的方式:

我创建了一个扩展:

extension PHAssetCollection {
var photosCount: Int {
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "mediaType == %d OR mediaType == %d", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
    let result = PHAsset.fetchAssets(in: self, options: fetchOptions)
    return result.count
}

}

然后在我获取对象的表视图控制器中,我创建了一个子类型数组(这不是为了获取所有 smartAlbums,而只是获取我需要的那个),并且我已经初始化了一个 PHCollection 类型的数组:

  let subtypes:[PHAssetCollectionSubtype] = [
    .smartAlbumFavorites,
    .smartAlbumPanoramas,
    .smartAlbumScreenshots,
    .smartAlbumSelfPortraits,
    .smartAlbumVideos,
    .smartAlbumRecentlyAdded,
    .smartAlbumSelfPortraits
]
var smartAlbums: [PHAssetCollection] = []

然后,我创建了一个函数来获取与子类型关联的所有 smartAlbum,并且其中至少有一个媒体(图像或视频 ->这是使用之前创建的扩展执行的):

private func fetchSmartCollections(with: PHAssetCollectionType, subtypes: [PHAssetCollectionSubtype]) -> [PHAssetCollection] {
    var collections:[PHAssetCollection] = []
    let options = PHFetchOptions()
    options.includeHiddenAssets = false
    for subtype in subtypes {
        if let collection = PHAssetCollection.fetchAssetCollections(with: with, subtype: subtype, options: options).firstObject, collection.photosCount > 0 { // .photosCount comes from extesion
            collections.append(collection)
        }
    }

在vieDidLoad中,我获取对象:

override func viewDidLoad() {
    super.viewDidLoad()
smartAlbums = fetchSmartCollections(with: .smartAlbum, subtypes: subtypes)
}

我对 swift 有点陌生,所以我无法判断这是否是最好的解决方案,但它有效,并且看到我在网上没有找到任何可以帮助我的东西,我想分享一下是否有人需要这个。

最新更新