创build相册的过滤PHAssetCollection失败

我需要创build一个过滤的SmartAlbums集合在UITable中显示。 我以前曾尝试过将未过滤的集合转换为可变forms,并删除我希望排除的那些,然后重新回到PHFetchResult。 所有这些尝试都失败了。

我现在正尝试使用PHFetch选项来过滤专辑(“ https://developer.apple.com/documentation/photos/phfetchoptions )”中的“localizedTitle”键。 但是,当我尝试尝试排除“Videos”智能文件夹的以下testing用例代码时,我在newAlbums中得到零计数结果。 当我将谓词设置为%K ==%@时,我也得到零结果。 正确答案应该是前者15,后者是1。 为什么我的谓词不能select正确的结果? 我不希望将新的集合保存到库中,只是将其用于临时显示,所以我没有尝试请求调用(也许我误解了这个框架?)

我search了S / O和developer.apple,工作代码的唯一例子是过滤单个媒体(照片或video),而不是selectsmartAlbums。

let fetchOptions = PHFetchOptions() let p1 = NSPredicate(format: "%K == %@", "localizedTitle", "Videos") fetchOptions.predicate = p1 let newAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: fetchOptions) 

这是我发现我已经validation工作的一种方法。 非常感谢Michael https://stackoverflow.com/a/46145638/4945371

首先添加这个不返回PHCollectionList的小方法,而是一个数组!

 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 { collections.append(collection) } } return collections } 

然后创build一个所需的智能相册数组:

  let subtypes:[PHAssetCollectionSubtype] = [ .smartAlbumFavorites, .smartAlbumLongExposures, .smartAlbumSelfPortraits, .smartAlbumRecentlyAdded // .smartAlbumUserLibrary, // .smartAlbumPanoramas, // .smartAlbumLivePhotos, // .smartAlbumBursts, // .smartAlbumDepthEffect, // .smartAlbumScreenshots, ] 

最后,

  smartAlbumsArray = fetchSmartCollections(with: .smartAlbum, subtypes: subtypes) 

而不是一些变体:

  smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: smartAlbumOptions)