Presenting Camera and Photo Gallery

camera-photo-library-swift

This tutorial will show you how to open a camera and photo library and also how to use the delegate methods to intercept the images and errors. The class contains code for:

  1. Presenting native camera.
  2. Presenting native camera with overlay view on top.
  3. Presenting photo library.

All you need to do is create a class, copy and paste this code and you are good to go.

import UIKit
@objc protocol photoHandlerDelegate{
    optional func photoPicked(img: UIImage)
}

class PhotoHandler: NSObject,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    let imagePicker = UIImagePickerController()
    var currentVC: UIViewController!
    var delegate: photoHandlerDelegate!
    static let sharedInstance = PhotoHandler()
    func showActionSheet(vc: UIViewController){
        currentVC = vc
        
        self.imagePicker.delegate = self
        let optionMenu = UIAlertController(title: nil, message: "Where would you like the image from?", preferredStyle: UIAlertControllerStyle.ActionSheet)
        
        let photoLibraryOption = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) -> Void in
            //shows the photo library
            self.imagePicker.allowsEditing = true
            self.imagePicker.sourceType = .PhotoLibrary
            self.imagePicker.modalPresentationStyle = .Popover
            vc.presentViewController(self.imagePicker, animated: true, completion: nil)
        })
        let cameraOption = UIAlertAction(title: "Take a photo", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) -> Void in
            //shows the camera
            self.imagePicker.allowsEditing = true
            self.imagePicker.sourceType = .Camera
            self.imagePicker.modalPresentationStyle = .Popover
            vc.presentViewController(self.imagePicker, animated: true, completion: nil)
            
        })
        let cancelOption = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
            (alert: UIAlertAction!) -> Void in
            vc.dismissViewControllerAnimated(true, completion: nil)
        })
        
        //Adding the actions to the action sheet. Camera will only show up as an option if the camera is available in the first place.
        optionMenu.addAction(photoLibraryOption)
        optionMenu.addAction(cancelOption)
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) == true {
            //Has Camera
            optionMenu.addAction(cameraOption)} else {
        }
        
        vc.presentViewController(optionMenu, animated: true, completion: nil)
    }
    func cameraWithOverlay(vc: UIViewController){
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) == true {
            currentVC = vc
            self.imagePicker.delegate = self
            self.imagePicker.allowsEditing = true
            self.imagePicker.sourceType = .Camera
            self.imagePicker.modalPresentationStyle = .OverCurrentContext
            self.imagePicker.cameraOverlayView = overlayView()
            vc.presentViewController(self.imagePicker, animated: true, completion: nil)
        }
    }
    func overlayView()-> UIView{
        let view = UIView(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.size.width,UIScreen.mainScreen().bounds.size.height - 60))
        let imgWidth: CGFloat = UIScreen.mainScreen().bounds.size.width
        let imgHeight: CGFloat = 260
        
        let y = UIScreen.mainScreen().bounds.size.height/CGFloat(2) - (imgHeight/CGFloat(2.5))
        
        let imgView = UIImageView(frame: CGRectMake(0,y,imgWidth,imgHeight))
        imgView.image = UIImage(named: "ic_template")
        imgView.contentMode = .ScaleAspectFit
        view.addSubview(imgView)
        return view
        
    }
    // MARK: - Image Picker Delegates
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print("finished picking image")
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //handle media here i.e. do stuff with photo
            let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            self.currentVC.dismissViewControllerAnimated(true, completion: { () -> Void in
                self.delegate.photoPicked!(chosenImage)
            })
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        //what happens when you cancel
        //which, in our case, is just to get rid of the photo picker which pops up
        currentVC.dismissViewControllerAnimated(true, completion: nil)
    }
}

 

Leave a Reply

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