Convert a PhotosPickerItem to an Image in SwiftUI on MacOS

I'm trying to provide a mechanism for the user to select a bg image from their photo library. I've got this code which theoretically is getting the data but can't figure out how to convert it to an Image in SwiftUI. I've found plenty of examples on iOS but none workable on MacOS.

This is my implementation of the PhotosPicker on iOS:

PhotosPicker(selection: $vm.selectedBGphoto, matching: .images) {
                    Label("Select Background Image", systemImage: "photo.on.rectangle")
                }
                .tint(.purple)
                .controlSize(.large)
                .onChange(of: vm.selectedBGphoto) { newItem in
                    Task {
   
                        if let data = try? await newItem?.loadTransferable(type: Data.self) {
                            if let uiImage = UIImage(data: data) {
                            vm.selectedBGdata = data
                                vm.bgImage = Image(uiImage: uiImage)
                        }
                    }
                }

This DOES NOT work on MacOS because of the UIImage reference. How do I convert what I get from PhotosPicker into an Image on MacOS?

Accepted Reply

I found that by processing the image as in the previous code I can simply display the image by var name:

// code here

//this displays the image that was picked from the PhotosPicker vm.bgImage .resizable() .frame(width: 200, height: 200) .scaledToFit() .opacity(vm.bgOpacity) .scaledToFit()

//code here

Replies

UI Elements (as in UIImage) are from UIKit which is the framework for iOS. Its equivalent for macOS is AppKit which uses NS Elements (as in NSImage). Lots of times they work in extremely similar ways. So you can use NSImage same way you would UIImage -> just do NSImage(data: data) to initalize an NSImage and then use it in SwiftUI with Image(nsImage: NSImage). If you're super used to typing out UIImage every time you could even do a typealias like this: typealias UIImage = NSImage to keep using the term UIImage in your macOS application.

Thanks for the reply. I went ahead and just implemented drag and drop on MacOS and that seems to work fine. I did get the PhotosPicker to run on iOS, so I will use it there.

I found that by processing the image as in the previous code I can simply display the image by var name:

// code here

//this displays the image that was picked from the PhotosPicker vm.bgImage .resizable() .frame(width: 200, height: 200) .scaledToFit() .opacity(vm.bgOpacity) .scaledToFit()

//code here