File naming, EXIF, CGImage and UIImage

Hi all.


I have a dilemma which leads me to strongly believe that I'm Doing It Wrong and missing something important, but I'm having a bit of trouble figuring out the expected/supported path for achieving this. So I'm hoping someone here can point me in the right direction.


I have a camera app I'm working on. It uses CoreImage to run some filters prior to saving the image. I am having difficulty achieving these two goals at the same time:


  1. Carrying through the original metadata (EXIF, etc.) from the AVCapturePhoto all the way through CoreImage filtering, to the final JPG or HEIF file.
  2. Saving to the photos library with the appropriate next sequential IMG_NNNN.EXT filename.


As far as I can tell, the only way to save to the photos library and get the default file naming behavior is to use PHAssetChangeRequest.creationRequestForAsset(from: UIImage). So at some point, I need to end up with an in-memory UIImage to save. However, I am unable to figure out how to get a UIImage that retains the metadata.


Also as far as I can tell, converting the AVCapturePhoto to a CIIimage causes a loss of the metadata. So I have been passing metadata as a separate variable along the side. And then the only way I have found to apply that metadata to the result is to convert the CIImage to a CGImage, and save it to a file-based CGImageDestination (because the properties get added in CGImageDestinationAddImage()). If I just use UIImage(CGImage), there's no way to pass in the metadata. If I use a CFMutableData CGImageDestination instead of a CFURL CGImageDestination, I can create a UIImage from that, but it doesn't get the metadata for some reason. Even saving to a file, and then loading it into a UIImage with UIImage(contentsOfFile) causes the metadata to be lost.


So the result is that what I've been doing is saving the CGImage to a temporary file, and then using PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: URL). This succeeds at saving an image with the correct metadata to the photos library. However, the saved image has the name that I used for my temporary file, not a standard "IMG_NNNN.EXT" name.


Theoretically I could query the photos library for the next available name, and manually use it, but that seems clunky and error-prone. I'm thinking that there must be some better way to do this, and I am probably making it way more complicated than it needs to be.


Suggestions?

Replies

TL;DR - Which Xcode, OS, etc.?


Ref. For Best Results - Read the Label