iOS Swift Image Picker example

UIImagePickerController has 3 available source types

  • .camera = Pulls up the Camera on the device. Make sure you check if camera is available before you provide this option.
  • .photoLibrary = Device's photo library as the source
  • .savedPhotosAlbum = Device's Camera Roll album as the source

iOS Swift Image Picker source types


You can allow the user to edit the image by setting the .allowsEditing = true
It allows the user to resize & crop after selecting or taking a picture.

The view controller delegate must implement both the UIImagePickerControllerDelegate and the UINavigationControllerDelegate protocols to be notified by the Image picker. One thing to keep in mind is that if you are allowing edit of the picture then use the .editedImage instead of the .originalImage inside the picker delegate to get the proper image from the image info dictionary.

iOS Swift Image Picker example

import UIKit

class ViewController: UIViewController,
                        UIImagePickerControllerDelegate,
                        UINavigationControllerDelegate {
    
    let imagePickerController = UIImagePickerController()
    let imageView = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "Main View"
        self.imagePickerController.delegate = self
        //allow editing of the image
        self.imagePickerController.allowsEditing = true
        
        //Button to Capture Image
        let button = UIButton(frame: CGRect(x: 50, y: 20, width: 200, height: 50))
        button.setTitle("Select a Picture", for: .normal)
        button.setTitleColor(.red, for: .normal)
        button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)
        button.layer.cornerRadius = 10;
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.black.cgColor
        button.clipsToBounds = true;
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        self.view.addSubview(button)
        
        imageView.frame = CGRect(x: 300, y: 20, width: 330, height: 330)
        imageView.contentMode = .scaleAspectFit
        view.addSubview(imageView)
        
        
    }
    
    @objc func buttonAction(sender: UIButton!) {
        if (sender.titleLabel?.text) != nil {
            
            // options: .Camera , .PhotoLibrary , .SavedPhotosAlbum
            let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                alert.addAction(UIAlertAction(title: "Camera",
                                              style: .default, handler: { _ in
                    self.imagePickerController.sourceType = .camera
                    self.present(self.imagePickerController, animated: true, completion: nil)
                }))
            }
            
            alert.addAction(UIAlertAction(title: "Photo Library",
                                          style: .default, handler: { _ in
                self.imagePickerController.sourceType = .photoLibrary
                self.present(self.imagePickerController, animated: true, completion: nil)
            }))
            
            alert.addAction(UIAlertAction(title: "Photo Albums",
                                          style: .default, handler: { _ in
                self.imagePickerController.sourceType = .savedPhotosAlbum
                self.present(self.imagePickerController, animated: true, completion: nil)
            }))
            
            alert.addAction(UIAlertAction.init(title: "Cancel",
                                               style: .cancel, handler: nil))
            
            //check if running on iPad
            switch UIDevice.current.userInterfaceIdiom {
            case .pad:
                alert.popoverPresentationController?.sourceView = sender
                alert.popoverPresentationController?.sourceRect = sender.bounds
                alert.popoverPresentationController?.permittedArrowDirections = .up
            default:
                break
            }
            
            self.present(alert, animated: true, completion: nil)
        }
    }
    
    @objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("Image Picker was cancelled...")
        self.imagePickerController.dismiss(animated: true, completion: nil)
    }
    
    @objc func imagePickerController(_ picker: UIImagePickerController,
            didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        
        guard let myImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
        else {
            print("Image not found...")
            return
        }
        
        self.imagePickerController.dismiss(animated: true, completion: nil)
        imageView.image = myImage
    }
    
}