[Code Snippets #1] iOS  Open Camera and Photo Library

[Code Snippets #1] iOS Open Camera and Photo Library

·

2 min read

  • Import UIImagePickerControllerDelegate and UINavigationControllerDelegatedekegates in your class declaration:
class ViewController: UIViewController, 
UIImagePickerControllerDelegate, 
UINavigationControllerDelegate {
   ...
}
  • Instantiate the Camera controller (usually inside a Button's action)
if UIImagePickerController.isSourceTypeAvailable(.camera) {
   let imagePicker = UIImagePickerController()
   imagePicker.delegate = self
   imagePicker.sourceType = .camera;
   imagePicker.allowsEditing = false // set it 'true' in case you want to crop an image into square
   present(imagePicker, animated: true, completion: nil)
}
  • Instantiate the Photo Library (usually inside a Button's action)
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary;
    imagePicker.allowsEditing = false // set it 'true' in case you want to crop an image into square
    present(imagePicker, animated: true, completion: nil)
}
  • Call the UIImagePickerController delegate inside the .swift file to get a UIImage
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
        myImg = image  // use the myImg UIImage as you wish
    }
    dismiss(animated: true, completion: nil)
}