Skip to content

Instantly share code, notes, and snippets.

@kitschpatrol
Created April 19, 2024 05:28
Show Gist options
  • Save kitschpatrol/4754b5cd67ba25dc41d7370855f9f193 to your computer and use it in GitHub Desktop.
Save kitschpatrol/4754b5cd67ba25dc41d7370855f9f193 to your computer and use it in GitHub Desktop.
Minimum viable Apple Photos library image export
import Foundation
import Cocoa
import Photos
class PhotoExporter {
let imageManager = PHImageManager.default()
func exportPhoto(withLocalIdentifier identifier: String, to destinationURL: URL) {
// Fetch the asset with the specified identifier
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil)
guard let asset = fetchResult.firstObject else {
print("No asset found with the specified identifier.")
return
}
// Request the image data for the asset
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.version = .current
options.deliveryMode = .highQualityFormat
options.isSynchronous = true
imageManager.requestImageDataAndOrientation(for: asset, options: options) { imageData, dataUTI, orientation, info in
guard let data = imageData else {
print("Failed to retrieve image data.")
return
}
// Write the image data to the destination URL
do {
try data.write(to: destinationURL)
print("Image exported successfully to \(destinationURL)")
} catch {
print("Failed to write image data to \(destinationURL): \(error)")
}
}
}
}
let exporter = PhotoExporter()
let photoIdentifier = "77758382-025A-446E-91C6-88A0BCAFDA91" // (Your photo UUID here)
let destinationPath = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)[0].appendingPathComponent("photokit-test.jpeg")
exporter.exportPhoto(withLocalIdentifier: photoIdentifier, to: destinationPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment