Created
September 21, 2024 01:20
-
-
Save melonamin/5673f0b465ccbed54287574e49aba1e3 to your computer and use it in GitHub Desktop.
Script to get filenames of Favorite photos from Photos.app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Photos | |
func requestPhotoLibraryAccess(completion: @escaping (Bool) -> Void) { | |
PHPhotoLibrary.requestAuthorization { status in | |
completion(status == .authorized) | |
} | |
} | |
func fetchFavoritePhotos(startDate: Date) -> PHFetchResult<PHAsset> { | |
let fetchOptions = PHFetchOptions() | |
fetchOptions.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ | |
NSPredicate(format: "favorite == YES"), | |
NSPredicate(format: "creationDate >= %@ AND creationDate <= %@", startDate as NSDate, Date() as NSDate) | |
]) | |
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] | |
return PHAsset.fetchAssets(with: fetchOptions) | |
} | |
func main() { | |
let args = CommandLine.arguments | |
var startDate: Date? | |
if args.count == 2 { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "yyyy-MM-dd" | |
startDate = dateFormatter.date(from: args[1]) | |
if startDate == nil { | |
print("Invalid date format. Please use YYYY-MM-DD.") | |
exit(1) | |
} | |
} else { | |
print("Usage: \(args[0]) start_date") | |
print("Date should be in YYYY-MM-DD format") | |
exit(1) | |
} | |
requestPhotoLibraryAccess { authorized in | |
guard authorized else { | |
print("Photo library access denied.") | |
exit(1) | |
} | |
let favorites = fetchFavoritePhotos(startDate: startDate!) | |
print("Found \(favorites.count) favorite photos from \(args[1]) to today.") | |
favorites.enumerateObjects { (asset, _, _) in | |
if let filename = asset.value(forKey: "filename") as? String { | |
print(filename) | |
} | |
} | |
exit(0) | |
} | |
} | |
main() | |
RunLoop.main.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment