Swift Camera Basics: Image Pickers and Action Sheets
An over on implementing camera selection and action sheets in Swift.
Feb 23, 2017 • Kevin Hou
I am designing and implementing a profile screen into Breathometer’s new app and one of the key components of many profile screens is a profile picture. I’m continuing to add to my toolbox of Swift skills so I set about learning how to get pictures from either the camera app or phone’s photo library.
We need to build some basic frontend components so that we can have control over our code:
ImageView: A view that our image from the camera/photo library will populate
Button: To control when we want to upload the image
Setup View Controller Class
In order to use photos from the device, you must use the UIImagePickerControllerDelegate and the UINavigationControllerDelegate. These will give you the necessary functions to be able to retrieve your first image. The UIImagePickerControllerDelegate is responsible for initiating an image picker controller which then piggybacks with the UINavigationControllerDelegate that allows you to present the image picker using presentViewController() and dismissViewControllerAnimated(). Your view controller class should look like this:
Connect Storyboard to Code
Create an outlet for the imageView and an action outlet for the button:
Setup Image Picker
Initialize the UIImagePickerController under the UIImageView outlet we created earlier:
Now we can create a function that will serve up the image picker. It accepts a sourceType as an input so that the image picker knows whether to show the actual camera interface or the photo library interface. There are three main parts in displaying an image picker: editing, source type, and presenting. Source type can be from the camera, the camera roll, or the photo library. The presentation component is what actually presents the imagePicker controller.
Create Action Sheet
We want the user to be able to specify if they want to use their camera or the photo library to select an image. We give them this option by creating an action sheet. An action sheet looks like this:
Because we want this action sheet to appear when the button is pressed, we place this bit of code in the action outlet. The code is straightforward and intuitive:
Setup the UIImagePickerControllerDelegate Methods
We must set the imagePicker delegate to self in viewDidLoad():
Now we can write the methods. There are two image picker functions are essential:
This function is triggered when you return a valid image. The selected image is passed in as part of the info object.
The complete source code looks like this:
Hope you found this helpful! You can find the source code on GitHub.
Another Example of an Action Sheet
Here’s another example of two different types of action sheets in case the first example was difficult to grasp.