SwiftUI PhotosPicker API - Return nil

Trying to follow along the code with PhotosPicker. It returns nil when loadTransferable(type:Image.self), and it works well using Data.self

Image supports only .png via its Transferable conformance in the current iOS 16 beta (tracked by 93125824).

Hello,

If you print the Image.transferRepresentation, you will see that it only supports a contentType of "public.png", which means loadTransferable(type:Image.self) will only return a non-nil success value if the PhotosPickerItem's supportedContentTypes also contains "public.png". That is not always the case, often times the supportedContentTypes contains jpeg or heic instead of png.

So, my recommendation is that you file an enhancement request for Image to support a contentType that is more flexible than just "public.png" using Feedback Assistant.

Once you've done that, I recommend that you continue to load the PhotosPickerItems as Data, and then create an image from this Data, for example:

import SwiftUI
import PhotosUI
import CoreTransferable

struct ContentView: View {
    
    @State var imageData: Data?
    @State var selectedItems: [PhotosPickerItem] = []
    
    var body: some View {
        
        VStack {
            if let imageData, let uiImage = UIImage(data: imageData) {
                Image(uiImage: uiImage).resizable()
            }
            Spacer()
            PhotosPicker(selection: $selectedItems,
                         maxSelectionCount: 1,
                         matching: .images) {
                Text("Pick Photo")
            }
            .onChange(of: selectedItems) { selectedItems in
                
                if let selectedItem = selectedItems.first {

                    selectedItem.loadTransferable(type: Data.self) { result in
                        switch result {
                        case .success(let imageData):
                            if let imageData {
                                self.imageData = imageData
                            } else {
                                print("No supported content type found.")
                            }
                        case .failure(let error):
                            fatalError(error.localizedDescription)
                        }
                    }
                }
            }
        }
    }
}

SwiftUI PhotosPicker API - Return nil
 
 
Q