代码之家  ›  专栏  ›  技术社区  ›  Phlippie Bosman

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

  •  7
  • Phlippie Bosman  · 技术社区  · 7 年前

    在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 回复  |  直到 7 年前
        1
  •  3
  •   Phlippie Bosman    7 年前

    如果不同时获取集合中的项目,则无法像这样过滤集合。看见 the docs

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

    因此,将其编码为:

    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
    }