通过PHAsset实时拍照和普通照片

时间:2018-03-23 10:09:52

标签: swift photos

我试图展示一系列照片。为了获得这些照片,我使用了Photos框架。

我使用以下代码来获取照片:

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

images = PHAsset.fetchAssets(with: .image, options: options)

但是,我也希望获得Live Photo(因此,两者的组合,Live Photo' s理想情况下只是第一个静止帧。

现在我知道你可以获得这样的实时照片:

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

options.predicate = NSPredicate(format: "(mediaSubtype & %d) != 0", PHAssetMediaSubtype.photoLive.rawValue)

images = PHAsset.fetchAssets(with: options)

但是,我不知道如何将两者组合在一起...有没有办法做到这一点,也许是通过创建两个NSPredicate

由于

1 个答案:

答案 0 :(得分:3)

以下是通过PHAsset获取实时照片和静态照片的方式:

第1步:创建NSPredicate以检测正常照片:

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

第2步:创建NSPredicate以检测实时照片:

let liveImagesPredicate = NSPredicate(format: "(mediaSubtype & %d) != 0", PHAssetMediaSubtype.photoLive.rawValue)

第3步:将两者结合使用NSCompoundPredicate

let compound = NSCompoundPredicate(orPredicateWithSubpredicates: [imagesPredicate, liveImagesPredicate])

第4步:将NSCompoundPredicate分配给PHFetchOptions

options.predicate = compound

第5步:享受!

所以在你的情况下:

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

// Get all still images
let imagesPredicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)

// Get all live photos
let liveImagesPredicate = NSPredicate(format: "(mediaSubtype & %d) != 0", PHAssetMediaSubtype.photoLive.rawValue)

// Combine the two predicates into a statement that checks if the asset
// complies to one of the predicates.
options.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [imagesPredicate, liveImagesPredicate])
相关问题