UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Importing Image into App

Forums > SwiftUI

Hello! I followed the tutorial https://www.hackingwithswift.com/books/ios-swiftui/importing-an-image-into-swiftui-using-uiimagepickercontroller to allow users to import their own photos in the app. I followed the tutorial closely but I have encountered some issues that I'm not sure how to fix.

struct SettingsBody: View {
    @State private var image: Image?
    @State private var filterIntensity = 0.5
    @State private var showingImagePicker = false
    @State private var inputImage = UIImage?.self

    var body: some View {
        NavigationView {
            VStack {
                ZStack {
                    Circle()
                        .scale(0.3)
                        .fill(Color.secondary.opacity(filterIntensity))

                    if image != nil {
                        image?.resizable().scaledToFit()
                    } else {
                        Image(systemName: "pencil")
                    }
                }.onTapGesture {
                    self.showingImagePicker = true
                }
                Text("Username")
            }
        }
    .navigationBarTitle("Settings")
        .sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {
            ImagePicker(image: $inputImage) // Error 1
        }
    }

    func loadImage() {
        guard let inputImage = inputImage else { return } // Error 2
        image = Image(uiImage: inputImage)
    }
}

The errors I am encountering are: Error 1: Cannot convert value of type 'Binding<UIImage?.Type>' to expected argument type 'Binding<UIImage?>' Error 2: Initializer for conditional binding must have Optional type, not 'UIImage?.Type'

For reference, this is the ImagePicker.swift file:

import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {

    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = uiImage
            }

            parent.presentationMode.wrappedValue.dismiss()
        }
    }

    @Environment(\.presentationMode) var presentationMode
    @Binding var image: UIImage?

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

    }
}

Really appreciate the help!!

2      

What you have done is instantiated the inputImage with a UIImage?.Type whereas what you want is just to declare it with a type UIImage? because thats what the ImagePicker is expecting. In your SettingsBody view you need to change the following -

@State private var inputImage = UIImage?.self

Change it to this -

@State private var inputImage: UIImage?

Once you do that it should be ok to go. Hope this helps.

Dave

2      

Hi, I followed your advice and removed the .self after the UIImage? but I'm getting another error (and not fixing the first two...)

The error is: Expected member name or constructor call after type name And the suggestions was to Use '.self' to reference the type object, which was why i added .self to my code.

Could there be an issue with my implementations in the other areas?

Thanks a lot!

2      

I tested your code and found the following:

Fix the type of inputImage: You have to specify the type, not assign a specific value. Simply replace your line with the one below (which @Newy11527 has also provided)

@State private var inputImage : UIImage?

This will solve the two errors, but a new one appears, because of missing self, which can be simply added.

ImagePicker(image: self.$inputImage)

After that, the code has no errors anymore.

2      

Hi, Sorry for the late reply but I managed to get it working!

Thanks a lot for your advice :)

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.