Search code examples
iosswiftswift4ios11ios12

How to fetch only image assets from smart albums with NSPredicate in Swift 4.2?


I want to fetch image assets from all smart albums on the users phone. At the moment I am fetching images and videos, but thats not what I want.

On my research I have always found the same solution but it doesn't seem to work any more since the questions are several years old now. So I can't find any up-to-date solution.

This is the solution I have found

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

let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions)
let fetchAssetsResult = PHAsset.fetchAssets(in: collection, options: fetchOptions)

On executing this lines of code I get the following error message

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported predicate in fetch options: mediaType == 1'

Is there any new working solution?


Solution

  • With the help of Bappaditya I have found out that I was using the predicate on the wrong asset fetch. The mediaType key is just for PHAsset.fetchAsset() and not for PHAssetCollection.fetchAssetCollection() as I was using it for.

    This code is working now

    let fetchOptions = PHFetchOptions()
    let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions)
    
    fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue)
    let fetchAssetsResult = PHAsset.fetchAssets(in: collection, options: fetchOptions)