Simple implementation of UIImagePickerController in Swift

Vitalii Zaitcev
3 min readDec 31, 2020

Selfie, memes, photos of your favorite pet, and any other types of images the user might want to share with the world! But how does someone can upload an image from their phone into the app? The answer is UIImagePickerController.

In this article, I’m going to provide a lightweight but expandable solution to how we can implement UIImagePickerController. Let’s create a new file and call it ImagePicker.swift and define a protocol for our case.

Looks easy, right?
lastPreparedImage keeps a reference to the last image selected by the user.
sourceType is a type of source from where the image will be taken from.
completion is a callback with a selected image.

Now we need to implement a custom class that is going to serve as a wrapper for UIImagePickerController.

A new class should be inherited from NSObject in order to confirm to UIImagePickerControllerDelegate and UINavigationControllerDelegate to get a callback with the selected image.

Depending on the setup of a view hierarchy, ParentViewController can be NavigationController, current ViewController, RootController, etc. It is possible to initialize ImagePicker outside of ViewController and inject it via init method but for the sake of simplicity, I’m going to create a new instance of this object right in there.

Let’s start our implementation by adding additional descriptions to our info.plist file. If we don’t app is going to crash. The key should match but a value can be any custom text, the user will see why do you need camera access.

Privacy — Camera Usage Description
Need to access your camera to capture a photo

Privacy — Photo Library Usage Description
Need to access your photo library to select a photo

And here is a simple ViewController:

And here is the result! The selected image will be available in a callback and we can use it to update imageView!

This setup can be easily extended by exposing any other properties of the UIImagePickerController under ImagePicker class.

--

--