SwiftUI Image from Data

Viewed 175

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 interprettedMP3 = 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?

2 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.

It depends on what you want... But the best way I think is to use the same way implemented before:

extension Image {
    
    init?(data: Data) {
        guard let image = UIImage(data: data) else { return nil }
        self = .init(uiImage: image)
    }
    
}
Related