imageswiftuiuiimagephotospicker

SwiftUI PhotosPicker image size {0,0} after converting with method .toUIImage()


Im trying to figure out why does my PhotosPicker image becomes {0,0} in size after successfully picking and displaying the picked image on my virtual device

     @State private var imageData: Data?
     @State private var avatarItem: PhotosPickerItem?
     @State private var avatarImage: Image?

     VStack{
            PhotosPicker("Select Image", selection: $avatarItem, matching: .images)
            avatarImage?
                .resizable()
                .frame(width: 200, height: 200)
                .scaledToFill()
                .clipShape(Circle())
        }
        .onChange(of: avatarItem){
            Task {
                if let loaded = try? await avatarItem?.loadTransferable(type: Image.self) {
                    avatarImage = loaded
                } else {
                    print("failed")
                }
            }
        }

When I tapped on this button:

        Button(action: {
            print("avatar Image: \(avatarImage)")
            // output: avatar Image: Optional(SwiftUI.Image(provider: SwiftUI.ImageProviderBox<SwiftUI.Image.(unknown context at $1c5c59f1c).CGImageProvider>))


            print("avatar Image: \(avatarImage?.toUIImage().size)")
            // output: avatar Image: Optional((0.0, 0.0))

            print("avatar image to UIImage: \(imageData)")
            // output: avatar image to UIImage: nil

        }, label: {
            Text("Register")
        })

Im trying to convert it into UIImage so I can use the .jpegData(compressionQuality: ) method to upload the image to Firebase storage

thanks


Solution

  • You can load the picker item as a Data:

    if let data = try? await avatarItem?.loadTransferable(type: Data.self) {
        imageData = data
    }
    

    If you don't necessarily need JPEG data, you can just upload imageData directly to Firebase.

    Otherwise, you can use imageData to construct a UIImage.

    Button("Register") {
        if let imageData {
            print(UIImage(data: imageData))
        }
    }