For UIImages I am writing images with EXIF/IPTC/etc meta using Photos like:
let dataBundle = mergeImageData(...)
let assetChangeRequest = PHAssetCreationRequest.forAsset()
let assetOptions = PHAssetResourceCreationOptions()
assetOptions.originalFilename = "\(fileName)"
assetChangeRequest.addResource(with: .photo, data: dataBundle, options: assetOptions)
PHPhotoLibrary.shared().performChanges({
...
})
func mergeImageData(image: UIImage, with metadata: NSDictionary) -> Data {}
But my app works with images that are potentially too large to read into memory and saves the image to Photos with a URL not a Data representation:
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: .photo, fileURL: imageFileURL, options: options)
I don't see any .meta option for adding a resource which seems like a shame. Is there anyway to add meta to an existing resource without reading it as a Data or UIImage?
The following is some code I have from an Objective-C project that is an extension to
NSURLfor getting and setting an image's caption. The code uses some lower level CoreGraphics code to read and write the image metadata without the need to load the image itself into memory. After the Objective-C code (which is working in a production app) I will post my the minimally tested Swift version of the code. One quick test with the Swift code worked. The Photos app was able to display the caption set on an image that was then saved to the photo library using aUIActivityViewController.Setting a
nilcaption removes any existing caption.BTW - this is the image caption that can be viewed and edited when viewing photos in the Photos app. If you set a caption with this code on an image and then save the image to the photo library then you will be able to see the caption. Or if you import an image from the photo library then this code can access the image's caption if it has one.
Objective-C code:
NSURL+Caption.h
NSURL+Caption.m
The Swift translation: