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

510 Views Asked by At

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)
1

There are 1 best solutions below

4
rkyr On BEST ANSWER

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
)