iosswiftmp3avurlasset

how to get mp3 file's artwork in swift(important because the objectc method doesn't work)


I found many oc method said using this code

*******metadata is a AVMetadataItem class

 NSString *path =[ [NSBundle mainBundle]  pathForResource:@"musicname" ofType:@"mp3"];

     NSURL  *fileURL = [NSURL  fileURLWithPath:path];

      AVURLAsset *avURLAsset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];

      for (NSSting *format  in [avURLAsset availableMetadataFormats]){

              for (AVMetadataItem *metadata in [avURLAsset metadataForFormat:format]){

                  if([metadata.commonKey isEqualToString:@"title"]){

                        NSSting *title = (NSSting *)metadata.value;

                   }

                  if([metadata.commonKey isEqualToString:@"artwork"]){

                       UIImage *coverImage = [UIImage imageWithData:[(NSDictionary *)metadata.value objectForKey:@"data"]];

                  }


               }

      }

I use swift to programming so i try to do that in swift like this

func getArtworkForTrack(trackNumber: Int) -> NSData {
    let asset = trackAVURLAssets[trackNumber]
    var artworkData: NSData = NSData()
    for metadata in asset.metadata {
        if let commonKey = metadata.commonKey {
            if commonKey == "artwork" {
                if let keySpace = metadata.keySpace {
                    if keySpace == AVMetadataKeySpaceiTunes {
                        print("keyspace == AVMetadataKeySpaceiTunes")
                        artworkData = (metadata.value?.copyWithZone(nil))! as! NSData
                    } else {
                        let dic = metadata.value as! NSDictionary
                        let image = UIImage(data: dic.objectForKey("data") as! NSData)
                    }
                }
            }
        }
    }

    return artworkData
}

But when I run , it comes a runtime error:

Could not cast value of type '__NSCFData' (0xbdbe94) to 'NSDictionary' (0xbdc394).
(lldb) 

at this line:

let dic = metadata.value as! NSDictionary

who can tell me how to solve the problem THX!


Solution

  • If an AVMetadataItem value is in raw data format, it should be accessible with .dataValue.

    In your case, probably something like this:

    if let data = metadata.dataValue {
        let image = UIImage(data: data)
    }