Can't get key value as String from metadata

626 Views Asked by At

I'm grabbing metadata from an MPMediaItem like this:

let url = item.value(forProperty:MPMediaItemPropertyAssetURL) as? NSURL
let asset = AVURLAsset(url: url! as URL, options: nil)
let metaArray = asset.metadata
for metadata in metaArray{
    print("-----metadata:\(metadata)")
    print("-----metadata.key:\(String(describing: metadata.key))")
}

However, when I get a block of metadata printed the "key" is printed as a numeric value instead of "pcst" as shown in the printout:

-----metadata:<AVMetadataItem: 0x1740153f0, identifier=itsk/pcst, keySpace=itsk, key class = __NSCFNumber, key=pcst, commonKey=(null), extendedLanguageTag=(null), dataType=com.apple.metadata.datatype.int8, time={INVALID}, duration={INVALID}, startDate=(null), extras={ dataLength = 1; dataType = 21; dataTypeNamespace = "com.apple.itunes"; }, value=1> -----metadata.key:Optional(1885565812)

This is happening for all of the metadata/keys (there are 29 in this particular media item).

Also note that this line of code:

let realString = NSString(string: metadata.key! as! String)

causes this error: Could not cast value of type '__NSCFNumber' (0x1b80dcdf0) to 'NSString' (0x1b80edae8).

How can I get the string value for the key ("pcst") ?

2

There are 2 best solutions below

10
On BEST ANSWER

May be what you are looking for is identifier property of AVMetadataItem.

for metadata in metaArray{
    print(metadata.identifier ?? "DefaultValue")       
}
0
On

In case others want to see the code I'm using:

func returnKeyString(_ inVal: String)->String{
    // expecting the metadata for "identifier" as input - returns key value
    // eg "itsk/ldes" ->  "ldes"
    // or "id3/%00WFD" etc.  -> "wfd"
    var sFinal:String = ""

    if (inVal.contains("/")){
        sFinal = (inVal.components(separatedBy: "/")[1])
    }
    if sFinal.contains("%"){
        sFinal = sFinal.components(separatedBy: "%")[1]
        let index1 = sFinal.index(sFinal.startIndex, offsetBy: 2)
        sFinal = sFinal.substring(from: index1)
    }
    return sFinal.lowercased()
}