Swift: 从图片库中获取不包含子类型的资源

Swift: get assets from Photo Library with excluding subtypes

我想从照片库中获取资产列表,但要从智能文件夹中排除子类型或资产,例如 smartAlbumBursts、smartAlbumLivePhotos、smartAlbumScreenshots

我的密码是

let options = PHFetchOptions()
options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: true) ]
options.predicate = predicate
let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)

我正试图做这样的谓词:

let predicateType = NSPredicate(format: "mediaSubtypes != %@", 
   PHAssetMediaSubtype.photoScreenshot as! CVarArg)

但是 1. 它崩溃了 2. 我只能为截图和 livePhoto 添加 PHAssetMediaSubtype 但不能为连拍照片添加 PHAssetMediaSubtype。

我知道有方法

if let collection = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, 
   subtype: .smartAlbumBursts, options: nil).firstObject {

但我不确定如何根据我的目的使用该方法或子类型

正在尝试使用 representsBurst 但发生崩溃:

let predicateType = NSPredicate(format: "representsBurst == %@", NSNumber(value: false))

reason: 'Unsupported predicate in fetch options: representsBurst == 0'

请参考PHFetchOptionssupported predicate and sort descriptor keys的table。

我假设如果资产不代表爆发,那么它就没有爆发标识符。你可以随意组合:

let options = PHFetchOptions()
options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: true) ]

// fetch all images with no burstIdentifier
options.predicate = NSPredicate(format: "burstIdentifier == nil")
var assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)

// fetch all images with photoScreenshot media subtype
options.predicate = NSPredicate(format: "((mediaSubtype & %d) != 0)", PHAssetMediaSubtype.photoScreenshot.rawValue)
assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)

// fetch all images with photoLive media subtype
options.predicate = NSPredicate(format: "((mediaSubtype & %d) != 0)", PHAssetMediaSubtype.photoLive.rawValue)
assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)

// fetch all non-photoScreenshot and non-photoLive images
options.predicate = NSPredicate(format: "NOT (((mediaSubtype & %d) != 0) || ((mediaSubtype & %d) != 0))", PHAssetMediaSubtype.photoScreenshot.rawValue, PHAssetMediaSubtype.photoLive.rawValue)
assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)

// fetch all non-photoScreenshot and non-photoLive images with no burstIdentifier
options.predicate = NSPredicate(format: "NOT (((mediaSubtype & %d) != 0) || ((mediaSubtype & %d) != 0)) && burstIdentifier == nil", PHAssetMediaSubtype.photoScreenshot.rawValue, PHAssetMediaSubtype.photoLive.rawValue)
assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)

NSPredicate 很棘手。 "not"的表达方式是这样的:

NSPredicate(
    format: "!((assetCollectionSubtype & %d) == %d)",
        PHAssetCollectionSubtype.smartAlbumBursts.rawValue)