我在这里使用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'
我知道这是一个很晚的答案,但是如果像我这样的人来了,您应该使用此方法来检索媒体类型。在这种情况下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)