Created
April 19, 2024 05:28
-
-
Save kitschpatrol/4754b5cd67ba25dc41d7370855f9f193 to your computer and use it in GitHub Desktop.
Minimum viable Apple Photos library image export
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 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