Image Picker in SwiftUI

Uplift iOS Interview

"Uplift iOS Interview" is a comprehensive guide to help aspiring iOS developers soar to new heights in their careers. This book is an indispensable tool for anyone looking to crack the iOS interview and impress their future employers with their technical prowess. With in-depth coverage of Swift, AutoLayout, SwiftUI, Multithreading, Memory management so on and so forth, this book is a treasure trove of knowledge for anyone looking to uplift their iOS development career.

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

Rev Up Your iOS Skills: Take a Dynamic Learning Journey
iOS Career Boost

iOS Career Boost is the ultimate learning journey to elevate your iOS development career through a dynamic blend of visual learning, handy cheat sheets, coding practice materials, and expertly curated tips and tricks


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. Your email address will only be used for the purpose of sending the newsletter and will not be shared with third parties or advertisers. Rest assured that we value your privacy and will not spam your inbox.


Connect with me on

Twitter and LinkedIn and don't hesitate to reach out with any questions about this post. Thank you for reading.

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