Image Picker in SwiftUI

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

Apple provides is the ability to allow users to select and upload images from their device’s photo library or camera.

To implement an image picker in SwiftUI, you will need to create an ImagePicker ViewController. This ViewController will allow the user to select a new picture from their photo library or by taking a new photo with their camera.

To specify whether the user will be selecting a photo from their library or taking a new photo with their camera, you will need to add a sourceType parameter.

You will also need to add a selectedImage and a Coordinator, which will allow you to preview the selected image in the View. This will give the user the opportunity to confirm their choice before updating their picture.

Here’s an example of how to use the ImagePicker struct to allow a user to select an image from their photo library:

struct ImagePicker: UIViewControllerRepresentable {
    @Environment(\.presentationMode) private var presentationMode
    var sourceType: UIImagePickerController.SourceType = .photoLibrary
    @Binding var selectedImage: UIImage

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

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

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

    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        var parent: ImagePicker

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

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

To enable the user to choose or take a new profile picture using the ImagePicker ViewController, you will need to add the following states to your View:

  • An image variable to store the selected image and pass it to the ImagePicker.
  • A showSheet state that can be toggled to display the ImagePicker as a sheet on top of the View.

You will also need to add onTapGesture to the View that the user can tap to show the ImagePicker. You can also include an Image view in the View so that the user can preview the image they have selected.

Note: By default, the ImagePicker will only allow the user to choose pictures or take pictures – videos are not included.

In order to ask the user for permission to access their camera, you will need to add a new key/value pair to your Info.plist file. To do this, go to the iOS folder and click on Info.plist. Add a new key and name it “Privacy – Camera Usage Description”. In the value column, specify why you need to use the camera.

// Full Code
struct ContentView: View {
    @State private var image = UIImage()
    @State private var isPhotoPickerPresented = false

    var body: some View {
        VStack {
            Image(uiImage: self.image)
                .resizable()
                .cornerRadius(100)
                .frame(width: 200, height: 200)
                .background(Color.white)
                .aspectRatio(contentMode: .fill)
                .clipShape(Circle())

            Text("Pick a photo")
                .font(.headline)
                .frame(maxWidth: .infinity)
                .frame(height: 40)
                .cornerRadius(10)
                .foregroundColor(.white)
                .onTapGesture {
                    isPhotoPickerPresented.toggle()
                }
        }
        .sheet(isPresented: $isPhotoPickerPresented) {
            ImagePicker(sourceType: .photoLibrary, selectedImage: self.$image)
        }
    }
}

To test the camera functionality of your app, you will need to use a physical device rather than the Simulator. You will need to connect your device to your Mac in order to test the camera on your device. It is not possible to test the camera on the Simulator.

Image Picker


✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.