Capture picture from iOS camera using Swift


To capture pictures from a camera in swift we can use AVFoundation which is a framework in iOS SDK, but we should try to avoid using it until we need a lot of custom features in our camera application. In this example, we’ll only capture a picture from the camera and display it on the view. We’ll be using image picker in this example instead of AVFoundation.

First, create a project and add an image view on its view Controller in the storyboard. Create the outlet in its class. Now inside the ViewController class conform it to −

class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate

After that create an objc function.

@objc func openCamera(){
}

Now in your View did load, add a tap gesture recognizer to your view controller, which should call an openCamera function when the screen is tapped.

override func viewDidLoad() {
   super.viewDidLoad()
   let gesture = UITapGestureRecognizer(target: self, action: #selector(openCamera))
   self.view.addGestureRecognizer(gesture)
}

Now In the function add following lines of code.

@objc func openCamera() {
   let imgPicker = UIImagePickerController()
   imgPicker.delegate = self
   imgPicker.sourceType = .camera
   imgPicker.allowsEditing = false
   imgPicker.showsCameraControls = true
   self.present(imgPicker, animated: true, completion: nil)
}

Once you have done the above steps, now we’ll implement the didFinishPickingMediaWithInfo method of UIImagePickerControllerDelegate and inside this method, we’ll get the image that the user captures up from the camera.

func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :
Any]) {
   if let img = info[UIImagePickerController.InfoKey.editedImage] as?
   UIImage {
         self.imgV.image = img
         self.dismiss(animated: true, completion: nil)
      }
      else {
         print("error")
      }
   }
}

Now, we need to add camera usage description key in our info.plist and give a description of why our application wants to use the camera. When we run this on an iPhone and capture image, this is the result that’s produced. Also, note that this application can not be run on a simulator.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements