SWIFT – Access iOS Camera and Photo Library

ios-camera-and-photo-library

Accessing iOS Camera and Photo Library is maybe one of the most common features that you can find in almost every app that we build. That’s why we have to make sure that we do it correctly and that we have a custom class ready to be reused at any time.

Recommended for you: How to convert HTML using NSAttributedString

In this tutorial, I will show you how to create the custom class in Swift, and have it by your hand whenever you need it. If you are lazy to read the whole tutorial, you have a GIST file at the bottom of this post that you can download. I will name the class CameraHandler.swift.

Access iOS Camera and Photo Library

I will start by creating two functions, the first will be named camera() and the second one photoLibrary(). We are using the UIImagePickerController class for both cases, and all we need to do is to change the sourceType property to the suitable one.

camera()

    func camera()
    {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let myPickerController = UIImagePickerController()
            myPickerController.delegate = self;
            myPickerController.sourceType = .camera
            currentVC.present(myPickerController, animated: true, completion: nil)
        }
        
    }
photoLibrary()

    func photoLibrary()
    {
        
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let myPickerController = UIImagePickerController()
            myPickerController.delegate = self;
            myPickerController.sourceType = .photoLibrary
            currentVC.present(myPickerController, animated: true, completion: nil)
        }
    }

As you can see, the sourceType changes to .camera and .photoLibrary types. We will need the UIImagePickerControllerDelegate and UINavigationControllerDelegate so we intercept the image that is picked by the user. I will explain below about the currentVC property.

Create UIActionSheet

Next, what we are going to do is create a function that will present both options to the user in a simple UIActionSheet. 

showActionSheet()

    func showActionSheet(vc: UIViewController) {
        currentVC = vc
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (alert:UIAlertAction!) -> Void in
            self.camera()
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (alert:UIAlertAction!) -> Void in
            self.photoLibrary()
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        
        vc.present(actionSheet, animated: true, completion: nil)
    }

This is the only function that you will need to call in order to show the iOS Camera and Photo Library. It is showing a simple UIActionSheet with the both options available. Also, we are passing a parameter called vc that will be passed to the currentVC private property. We are doing this in order to handle the presentation of the controllers directly from inside the class.

NOTE: If the device doesn’t supports camera or photo library, nothing will happen when you press an option. For example, testing the camera feature on simulator.

Recommended for you: Swift 4 – Top 3 New String API Features

Delegate methods

At the end of the file in we will create an extension, and we will call the delegate methods didFinishPickingMediaInfo and imagePickerControllerDidCancel that belongs to the UIImagePickerControllerDelegate.

extension CameraHandler: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        currentVC.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            self.imagePickedBlock?(image)
        }else{
            print("Something went wrong")
        }
        currentVC.dismiss(animated: true, completion: nil)
    }
}

We are now able to get the picked image from the photo library or the captured one from the camera. To make things simpler and clearer, I have created a closure named imagePickedBlock() that will provide us with the picked image where we need it. Here are all the properties that you will need.

static let shared = CameraHandler()
    
fileprivate var currentVC: UIViewController!
    
//MARK: Internal Properties
var imagePickedBlock: ((UIImage) -> Void)?

How to use?

We are done creating the class now we need to use it. The beauty in classes like this one is the easy reuse.

CameraHandler.shared.showActionSheet(vc: self)
CameraHandler.shared.imagePickedBlock = { (image) in
    /* get your image here */
}

That’s it from this tutorial that showed you how to access iOS Camera and Photo Library in Swift 3, and I really hope that it helped you. Please do share this post as a support or comment in the comment section for any questions that you might have.

The complete GIST file can be found here.
Follow me on Medium, for more interesting Swift programming tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *