6

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?

anton68
  • 387
  • 3
  • 14

2 Answers2

11

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)
anton68
  • 387
  • 3
  • 14
3

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

Bappaditya
  • 9,494
  • 3
  • 20
  • 29
  • This doesn't seem to affect the media type or am I wrong? I still want to fetch all albums with all the content, but only the images not videos. – anton68 Dec 30 '18 at 11:49
  • updated my answer with supported keys for `PHFetchOptions` – Bappaditya Dec 30 '18 at 12:04
  • So whats the reason then that I get the error message for an unsupported predicate? MediaType is in the list of supported keys. Is my syntax wrong? – anton68 Dec 30 '18 at 12:30
  • I think I have found the problem! I will give an answer to myself. – anton68 Dec 30 '18 at 12:36