Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Image from Data

Tags:

swift

swiftui

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?

like image 973
Luke Price Avatar asked Dec 05 '25 11:12

Luke Price


1 Answers

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.

like image 51
Asperi Avatar answered Dec 07 '25 15:12

Asperi