19

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?

1

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a fix, but not ideal since unfortunately there is an issue on image scaling if you convert from UIImage to Image. Apple need to fix this.
-3

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)
    }
    
}

3 Comments

There is no UIImage for macOS/AppKit.
What is the problem with using the same code with NSImage?
That is not what your posted code does and if this is what you mean with your answer it’s not very clear (hence my comment) and maybe you should improve it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.