Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
anton68 Avatar asked Dec 30 '18 11:12

anton68


2 Answers

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)
like image 59
anton68 Avatar answered Nov 03 '22 07:11

anton68


Try,

let albumName = "Your Album Name" or "Your Album Local Identifier"
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let fetchResult: PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

The supported keys are,

Image

For more details please refer PHFetchOptions

like image 40
Bappaditya Avatar answered Nov 03 '22 07:11

Bappaditya