【问题标题】:How to fetch only image assets from smart albums with NSPredicate in Swift 4.2?如何在 Swift 4.2 中使用 NSPredicate 仅从智能相册中获取图像资产?
【发布时间】:2019-05-27 09:16:17
【问题描述】:

我想从用户手机上的所有智能相册中获取图片资源。目前我正在获取图像和视频,但这不是我想要的。

在我的研究中,我总是找到相同的解决方案,但它似乎不再起作用,因为这些问题已经存在好几年了。所以我找不到任何最新的解决方案。

这是我找到的解决方案

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)

let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions)
let fetchAssetsResult = PHAsset.fetchAssets(in: collection, options: fetchOptions)

在执行这行代码时,我收到以下错误消息

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch options: mediaType == 1'

有什么新的可行的解决方案吗?

【问题讨论】:

    标签: ios swift swift4 ios11 ios12


    【解决方案1】:

    在 Bappaditya 的帮助下,我发现我在错误的资产获取上使用了谓词。 mediaType 键仅适用于PHAsset.fetchAsset(),而不是我使用它的PHAssetCollection.fetchAssetCollection()

    此代码正在运行

    let fetchOptions = PHFetchOptions()
    let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions)
    
    fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue)
    let fetchAssetsResult = PHAsset.fetchAssets(in: collection, options: fetchOptions)
    

    【讨论】:

    • 完美,我只需要找到视频,而且效果也很好。
    【解决方案2】:

    试试,

    let albumName = "Your Album Name" or "Your Album Local Identifier"
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
    let fetchResult: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
    

    支持的键是,

    更多详情请参考PHFetchOptions

    【讨论】:

    • 这似乎不会影响媒体类型还是我错了?我仍然想获取包含所有内容的所有相册,但只获取图像而不是视频。
    • PHFetchOptions支持的密钥更新了我的答案
    • 那么我收到有关不受支持的谓词的错误消息的原因是什么? MediaType 在支持的键列表中。我的语法错了吗?
    • 我想我找到了问题所在!我会给自己一个答案。
    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多