Gizmodo
Gizmodo

Reputation: 3222

PHFetchOptions() Photos Only Using PHAsset & PHAssetCollection

I am using a chunk from Apple's sample code here:

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)
}

This lists all Albums successfully.

What I Need:

I want to only list albums with photos, exclude videos. Also, exclude video's from getting listed inside of albums, such as inside "All Photos".

What I tried:

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

This causes to crash saying 'Unsupported predicate in fetch options: mediaType == 1'

Upvotes: 3

Views: 4270

Answers (2)

Eric Yuan
Eric Yuan

Reputation: 1472

So far it works fine to me :

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)

Upvotes: 1

dequin
dequin

Reputation: 926

I know this is a very late answer, but in case someone like me gets here, you should use this method to retrieve a media type. In this case PHAssetMediaType.image

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

So in Swift 5 it writes as

let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)

Upvotes: 4

Related Questions