7

I am trying to add metadata to my synthetically generated and save it to camera roll by using the Photos framework. I got the saving and editing working but I just can seem to figure out how to add metadata. I have tried many approaches like adding the metadata by creating a CoreGraphics image (see code below). All these approaches do not give me an error but I just cannot see the metadata when I open the image on my Mac.

Can anyone point me in the right direction here?

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assets : PHFetchResult = PHAsset.fetchAssetsWithLocalIdentifiers([self.localIdentifier], options: nil);
let asset : PHAsset = assets[0] as! PHAsset;
let changeRequest = PHAssetChangeRequest(forAsset: asset);
changeRequest.location = self.currentLocation;

asset.requestContentEditingInputWithOptions(nil, completionHandler: { (input: PHContentEditingInput?,
    info: [NSObject : AnyObject]) -> Void in


    guard let input = input else { return }

    let imageManager : PHImageManager = PHImageManager();
    let requestoptions : PHImageRequestOptions = PHImageRequestOptions();
    requestoptions.resizeMode = PHImageRequestOptionsResizeMode.None;

    imageManager.requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: PHImageContentMode.Default, options: PHImageRequestOptions(), resultHandler: { (let image : UIImage?, _) -> Void in

        let output : PHContentEditingOutput = PHContentEditingOutput(contentEditingInput: input);

        PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in

            let changeRequest = PHAssetChangeRequest(forAsset: asset);

            /* Neu */
            let imageData : NSData = NSData(contentsOfURL: (input.fullSizeImageURL)!)!;
            let image : CIImage = CIImage(data: imageData)!;
            let dataPtr = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(imageData.bytes), imageData.length)


            // Save off the properties
            let imageSource : CGImageSourceRef = CGImageSourceCreateWithData(dataPtr, nil)!;
            var metadata : NSMutableDictionary = NSMutableDictionary(dictionary: CGImageSourceCopyProperties(imageSource, nil)!);



/* Add some values to metadata */
....

            NSLog("New metadata: %@", metadata);

            // Save the image
            let outputImageSource : CGImageSourceRef = CGImageSourceCreateWithData(dataPtr, nil)!;
            let jpegData : CFMutableDataRef = CFDataCreateMutable(kCFAllocatorDefault, 0);
            let outputDestination : CGImageDestinationRef = CGImageDestinationCreateWithData(jpegData, CGImageSourceGetType(outputImageSource)!, 1, nil)!;

            // add the image data to the destination
            CGImageDestinationAddImageFromSource(outputDestination, outputImageSource, 0, metadata);

            if CGImageDestinationFinalize(outputDestination)
            {
                NSLog("Successful image creation.");
                // process the image rendering, adjustment data creation and finalize the asset edit.
            }
            else
            {
                NSLog("Image creation failed.");
            }



            (jpegData as NSData).writeToURL(output.renderedContentURL, atomically: true);


            let options : String = NSString(format: "%f|%f|%f|%f|%f|%f", self.saturationSlider.value, self.warmthSlider.value, self.brightnessSlider.value, self.sharpnessSlider.value, self.contrastSlider.value, self.gammaSlider.value ) as String;
            let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"];

            output.adjustmentData = PHAdjustmentData(formatIdentifier: NSBundle.mainBundle().bundleIdentifier!,
                formatVersion: nsObject as! String,
                data: options.dataUsingEncoding(NSUTF8StringEncoding)!);

            changeRequest.contentEditingOutput = output;

            }, completionHandler: { (_bool, _error) -> Void in
                if !_bool && error != nil
                {
                    NSLog("%@", error!);
                }
        });
    });
});
}, completionHandler: { (_bool, _error) -> Void in
});
2
  • Over a year later here but I'm finding the same results. No errors, but no custom metadata, either. While the Photos framework advertises "editing metadata" for an asset, it clearly does not offer editing of actual EXIF-type metadata.
    – snakeoil
    Commented Dec 7, 2016 at 22:44
  • I've bumped into the same issue. I posted my own version of this question stackoverflow.com/questions/48255636/…. It appears editing exif properties works if the image already has a PHAdjustmentData attached from another application. I eventually gave up and added an id to the exif comment property on image creation and used this to index a dictionary that stored additional metadata I stored in Core Data. Commented Jan 19, 2018 at 16:44

1 Answer 1

-3

You can add/set a few properties on the creationRequest object. I don't know about adding custom metadata.

PHPhotoLibrary.shared().performChanges({

    let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: self.anImage!)

    let aLocation = CLLocation(latitude: 27.63866, longitude: -80.39707)

    creationRequest.location = aLocation

    creationRequest.isFavorite = true

    creationRequest.creationDate = Date()

}, completionHandler: {success, error in
    if !success {
        print("error creating asset: \(error!)")
    } else {
        print("success creating asset!")
    }
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.