I am making a multi-platform SwiftUI app that loads the song artwork from an .mp3 file
let playerItem = AVPlayerItem(url: fileURL)
let metadataList = playerItem.asset.metadata
for item in metadataList {
guard let key = item.commonKey, let value = item.value else {
continue
}
switch key {
case .commonKeyArtwork where value is Data :
let songArtwork = UIImage(data: value as! Data)!
default:
continue
}
}
I can also get data by using
let interpretedMP3 = AVAsset(url: fileURL)
and the metadata from that.
This all works fine for ios using UIImage(data: value as! Data)! but macos doesn't support uiimage so how am I supposed to make an image from this data?
It is possible to make some platform-depedent image builder, like
func createImage(_ value: Data) -> Image {
#if canImport(UIKit)
let songArtwork: UIImage = UIImage(data: value) ?? UIImage()
return Image(uiImage: songArtwork)
#elseif canImport(AppKit)
let songArtwork: NSImage = NSImage(data: value) ?? NSImage()
return Image(nsImage: songArtwork)
#else
return Image(systemImage: "some_default")
#endif
}
*Note: actually it can be also used #if os(iOS) etc, but Apple does not recommend to check OS directly until it is really needed explicit platform knowledge, but instead check API like above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With