Most performant method to fetch just images from a collection

It was discussed in What's New in Photos APIs at WWDC that we should avoid using NSPredicate for custom fetch options if at all possible for performance purposes. In my app, I'm using NSPredicate to get only images from the user's library. I'm not seeing an API that would allow me to get assets from a specific collection filtered to just images without the use of NSPredicate though. Is there a more efficient way to perform this query that I'm not seeing?


let photoLibraryFetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
let assetCollection = photoLibraryFetchResult.firstObject!

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

let fetchResults = PHAsset.fetchAssets(in: assetCollection, options: fetchOptions)
Add a Comment

Replies

Is Core Data part of that app's context?

Unfortunately, it's definitely a lot slower to filter large photo libraries by mediaType. I just verified this by testing with a library of 140,000 photos, and it takes 3-5 seconds to load fetch results that are filtered by PHAssetMediaType.image, whereas a request sans predicate loads almost instantly. Notably, this same performance problem seems to exist when using UIImagePickerController, which defaults to only showing results for still images. Since I don't see another workaround, I'm considering just loading everything and then hackily hiding videos in the UICollectionView...