Search code examples
iosswiftnspredicatephotosframework

Swift: how to set range of photos between 2 dates?


I want to get photos from Photo Library from 1 of January to 1 of May How can I do that

my code is for all photos:

let options = PHFetchOptions()
options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: true) ]
options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let assets = PHAsset.fetchAssets(with: options)

Solution

  • There's a creationDate attribute, so you can extend your predicate to filter dates:

    (creationDate >= %@) AND (creationDate <= %@)
    

    So your predicate should look something like the following

    options.predicate = NSPredicate(
      format: "mediaType = %d AND (creationDate >= %@) AND (creationDate <= %@)", 
      PHAssetMediaType.image.rawValue, 
      fromDate as NSDate, 
      toDate as NSDate
    )