Open the native iOS Camera and Photo Library in Swift – XSTutorials

Open the native iOS Camera and Photo Library in Swift

PLEASE NOTE: This tutorial has been written using XCode 10 and Swift 5

The most downloaded apps nowadays come from the Photography category. Many other applications also need to take pictures with the built-in camera or pick images from the photo library, so it’ important to know how to use the iOS Image Picker to open the native device’s Camera and Photo Gallery and get the selected image for further use.

It’s pretty easy, and we’ll now see how to make it.

The Xcode project

Let’s open a blank Xcode project, select Single View App, give it a name like CameraLibrary, set the Organization identifier as you wish, choose Swift as language and click the Next button. Save this project on your Desktop or in any folder you wish.

Open a new Xcode project
Set the project’s info

In order to make this app work on older devices, set the Deployment Target as 9.0 and check the Requires full screen option in the General tab in Xcode

The app design

Open the Main.storyboard file from the left panel, that’s the interface where you will place your Views and design your app’s look. With Xcode 10, the device layout you will get is of an iPhone XR, but you’re free to select any device by clicking the View as: iPhone Xr button on the bottom of the window:

So now we need to drag an UIButton into our Controller and declare its IBAction in the ViewController.swift file. In order for you to do that, click the Library button on the top-right corner of the Xcode window and type “button” in the search field of the popup that will show up.

Find the Button view in the Library popup window

Click and hold the Button cell, and simply drag it into the Controller. Move it on the bottom of the screen, because you’ll have to add other Views. If you double-click on the UIButton you’ll be able to give it a title. Do that and type Camera, then hit Enter.

Set Button’s title

You have now 2 ways to add a new UIButton (the one that will open the Photo Library):

  • Repeat the steps above
  • Hold the alt key, click and hold the Camera button and drag it down

The second option is the one I prefer, especially if I haven’t declared any View or IBAction in the swift file yet. Try that, it’s quick and cool, just position the new UIButton below the Camera one, and double-click on it to type the Photo Library title (like you did for the first Button).

It’s time to drag an UIImageView in the Controller. This ImageView will show the picked or taken picture in your application.

As you’ve done before to add the first UIButton, open the Library popup again, type “imageview“, drag the ImageView cell on the top of the screen’s area and give it a size of 300×300.

Add a UIImageView to your Controller

You can adjust the margins, position and size of your Views by selecting them and opening the Size Inspector panel (the one with the ruler icon). I won’t get into details about this panel now, you may read this tutorial to learn more about the Xcode interface and commands.

The design job is done, it doesn’t look like a professional app but it doesn’t matter right now, we’re here to learn how to code, first 🙂

You have to declare an IBOutlet of your ImageView and 2 IBActions for your Buttons in the ViewController.swift file. It’s pretty easy, the first step is to open the Assistant Editor by clicking the 2-circle button on the top-right corner of Xcode. This will split the middle Xcode window into two areas, the left one will still show the Main.storyboard window, the right one will show the code from the ViewController.swift file.

In order for you to declare your ImageView’s IBOutlet into the ViewController.swift file is to click and hold the ctrl key, click and hold the left mouse button and the mouse pointer above this line:

override func viewDidLoad() {

Xcode will show a blue line that will help you to position your mouse pointer in the .swift file. Release the mouse button and a small popup box will appear – it’s the declaration infobox. Type myImage in the Name field and click the small Connect button (or just hit Enter).

An IBOutlet is the View itself, an IBAction is a function that will execute your code, that’s why Buttons, Gestures, and other Views have the option to be declared as both IBOutlet and IBAction, while ImageViews or Labels offer only the IBOutlet option.

Now it’s time to connect the two IBActions for the Camera and Photo Library buttons, the process is similar to the one we just performed for the myImage ImageView, the only thing that changes is that we’ll have to select the Action option from the Connection field.

So drag the blue line from the Camera button below the closure of the viewDidLoad() functionIBActions can be declared only outside functions inside a Swift Class. Select Action, and type cameraButt in the Name field, then hit Enter. Do the same for the Photo Library button (type photoLibraryButt in the Name field this time).

The code

At this point, we’re finally ready to write some code, so let’s start by adding the necessary Delegate calls next to the UIViewController class name. Type a comma (,) next to UIViewController and start typing “imagepickerdelegate“. XCode will prompt a list of options based on your keywords, select the UIImagePickerControllerDelegate one.

Delegate names must be separated by a comma, so type it (,) and start typing “navigationcontroller“, then choose the UINavigationControllerDelegate option.

Add the UINavigationControllerDelegate protocol

Delegate Protocols allow you to use their proper functions in your Swift class. In this case, we’ll call the didFinishPickingMediaWithInfo function from the UIImagePickerControllerDelegate to get our picked image and show it into the myImage ImageView.

Place your mouse pointer below this code:

@IBAction func photoLibrary(_ sender: Any) {
}

  Start typing “imagepickerdidfinish” and select the blue option that will popup.

Call the didFinishPickingMediaWithInfo delegate function

Inside that function, paste this code:

if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
    myImage.image = image
}
dismiss(animated: true, completion: nil) 
Write the code that handles a picked image

The code you’ve just pasted sets the UIImage called image as the image of our myImage ImageView, then it dismisses the UIImagePickerController, either the native Camera or Photo Library screen.

We have now to open those screens from the Button Actions we previously declared. Add the following code inside the cameraButt() function:

if UIImagePickerController.isSourceTypeAvailable(.camera) {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera;
    imagePicker.allowsEditing = false
    present(imagePicker, animated: true, completion: nil)
} 

The lines of code above do the following:

  1. Check for the availability of the native Camera
  2. Instantiate a new UIImagePickerController
  3. Set the UIImagePickerController‘s delegate
  4. Set the source type as Camera
  5. Does not allow editing after picking the picture (which means that a black screen with a square frame will not be displayed after taking a photo, but the picture will be processed and added right away)
  6. Present the UIImagePickerController with the default iOS animation

Now add the following lines inside the photoLibraryButt() IBAction

if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary;
    imagePicker.allowsEditing = false
    present(imagePicker, animated: true, completion: nil)
} 

The code above performs almost the same operations like the one into the cameraButt() does, although it checks for the Photo Library availability and sets the source type as Photo Library.

TIP: If you want to allow image editing, just switch false into true in the imagePicker.allowsEditing = false line

The last thing to do is to add a few Privacy lines in the Info.plist file that will be needed to the app to ask for Camera and Photo Library permissions. In fact, is you ran the app now and tap the Camera button, for instance, the app would crash and show you this message in the Console:

This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSCameraUsageDescription key with a string value explaining to the user how the app uses this data. 

So select the Info.plist file from the files list on the right-side panel, click on any (+) button at the end of a row, scroll down to the Privacy – Camera Usage Description and select it.

Add the Privacy – Camera Usage Description option in Info.plist

In the empty row next to Privacy – Camera Usage Description one, type something like “This app needs to use your Camera to take pictures“. This text will be shown in the Permission Alert after trying to open the Camera for the first time.

Now click again another (+) button to add a new row, scroll down to Privacy – Photo Library Usage Description and select it. In the empty row next to it, type something like “This app needs to use your Photo Library to take pictures“. This text will be shown in the Permission Alert after trying to open the Photo Library for the first time.

Set Privacy Permission rows and strings

You are ready to run your app and test it out now. Plug your device into the USB port of your Mac with the right cable and select it from the devices list.

Select your device

NOTE: The reason why I suggest you to run the app on a real device is that the iOS Simulator doesn’t support Camera, so you wouldn’t be able to test the application on a Simulator.

Once you tap the Camera button, this is the alert you’ll get:

Of course, tap OK and take a picture.

If you select the Photo Library button, the iOS default Camera Roll will show up. Select a picture and you’ll see it in the Home screen os your app.

Conclusion

That’s all for this tutorial, you have learned how to create an Xcode project from scratch, add some Views in the Storyboard and call the native iOS Camera and Photo Library controllers to get images and display them into an UIImageView.

Hope you enjoyed this article, feel free to post comments about it. You can also download the full Xcode project of this tutorial, just click the link below:

Download the Xcode project

Buy me a coffee - XScoder - thanks for your support
Your support will be highly appreciated 😉