3

我在这里使用了 Apple 示例代码中的一部分:

override func awakeFromNib() {
    // Create a PHFetchResult object for each section in the table view.
    let allPhotosOptions = PHFetchOptions()
    allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let allPhotos = PHAsset.fetchAssetsWithOptions(allPhotosOptions)
    let smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .AlbumRegular, options: nil)

    let topLevelUserCollections = PHCollectionList.fetchTopLevelUserCollectionsWithOptions(nil)

    // Store the PHFetchResult objects and localized titles for each section.
    self.sectionFetchResults = [allPhotos, smartAlbums, topLevelUserCollections]
    self.sectionLocalizedTitles = ["", NSLocalizedString("Smart Albums", comment: ""), NSLocalizedString("Albums", comment: "")]

    PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}

这成功列出了所有专辑。

我需要的:

我只想列出带照片的相册,排除视频。此外,将视频排除在相册中,例如在“所有照片”中。

我尝试了什么:

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

这会导致崩溃说“获取选项中不受支持的谓词:mediaType == 1”

4

2 回答 2

2

我知道这是一个很晚的答案,但是如果像我这样的人来到这里,您应该使用此方法来检索媒体类型。在这种情况下,PHAssetMediaType.image

func fetchAssets(with mediaType: PHAssetMediaType, options: PHFetchOptions?) -> PHFetchResult<PHAsset>

所以在 Swift 5 中它写成

let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)
于 2020-01-21T20:07:48.697 回答
1

到目前为止,它对我来说很好:

let allAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
let someAlbum = allAlbums.object(at: 0)
let onlyPhotoOption = PHFetchOptions()
onlyPhotoOption.predicate = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
let photos = PHAsset.fetchAssets(in: someAlbum, options: onlyPhotoOption)
于 2021-08-01T08:08:35.173 回答