Writing MP4 metadata with AVFoundation

I have been banging my head against the wall for days trying to find any solution that will allow me to write arbitrary metadata into an MP4 using AVFoundation. Both AVAssetWriter and AVAssetExportSession have metadata API that look for all to see like they should do the trick of writing metadata, but having tried and tried again to add metadata via these APIs, the metadata is never written. Are they any examples of actually successfully writing metadata to an MP4 with AVFoundation?

Here's an example that seems like it should work, but doesn't:

Code Block swift
        let myMetadata = AVMutableMetadataItem()
        myMetadata.identifier = AVMetadataIdentifier(rawValue: "udta/GPMF")
        myMetadata.value = "Yo, dawg, I'm metadata" as NSString
        myMetadata.dataType = kCMMetadataBaseDataType_RawData as String
        exporter?.metadata = [myMetadata]
// export.exportAsynchronously()...


And this doesn't work either:

Code Block swift
let foo = AVMutableMetadataItem()
foo.value = gpmf.dataValue! as NSData // this is copying data directly from AVMetadataItem taken from an AVAsset I have which already has metadata
assetWriter.metadata = [foo]
assetWriter.startWriting()
// assetWriter.finishWriting


To write a custom metadata identifier to ISO userdata, try prefixing your identifier with "uiso" instead of "udta" and convert your string to data when setting it as the value. I don't think you need to set the data type for static metadata, but if you do then RawData seems like a reasonable choice.

the AVMetadataItem writing indeed seems fraught with peril. i tried a bunch of examples with basic stuff like title and description in the "common" metadata family, and none of them seem to write data to the file using AVAssetWriter for mp4 files. checked by mpls command line. does anyone know the difference between the .key and the .identifier ? i see examples with .key and examples with .identifier. why we should use one over the other = ?

Writing MP4 metadata with AVFoundation
 
 
Q