1

I need to fetch three photos sorted by the date taken - latest being the most recently taken. The way I am currently doing this is by fetching all photo assets then fetching the asset at the appropriate indexes (0, 1, 2). While this works, I am curious if there is a more efficient way to do this when I'm only interested in the top three. The docs explain the fetch doesn't return all image data - only metadata, but I still don't need to obtain all of the metadata. Is there a PHFetchOption I could use to limit the fetch, or an NSPredicate, or is that not necessary to worry about?

var assetsFetchResults = PHAsset.fetchAssetsWithMediaType(.Image, options: nil)
let imageManager = PHCachingImageManager()

if assetsFetchResults?.count > 0 {
    var asset = assetsFetchResults?[0] as? PHAsset
    imageManager.requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: nil, resultHandler: ...)
}
//repeat for index 1 and 2 
Jordan H
  • 52,571
  • 37
  • 201
  • 351
  • 1
    You can use `fetchKeyAssetsInAssetCollection:options:` to fetch a few KEY photos instead of `fetchAssetsInAssetCollection:options:options:` – k06a Jun 01 '15 at 23:01
  • This does not work in case of app specific user libraries. – jarora Jun 07 '15 at 11:33
  • @jarora It worked for me in iOS 8.4.1 in an album created by a third-party app – Jordan H Sep 07 '15 at 03:13

1 Answers1

7

so with iOS 9 you can set PHFetchOptions setting to limit how many you fetch. For example:

   let fetchOptions = PHFetchOptions()
    if #available(iOS 9.0, *) {
        fetchOptions.fetchLimit = 3
    } else {
        // Fallback on earlier versions
    }

However I am also looking for a way to do this on iOS 8 devices as we still have to support both iOS 8 and 9 at this point

MadeByDouglas
  • 2,509
  • 1
  • 18
  • 22