How to use the front camera in Swift?


To use the front camera in swift we first need to get a list of cameras available in the device we are using. In this article we’ll see how to get the list of devices and then check if the front camera is available or not. We’ll do it in a series of steps.

Import AVFoundation

Check if the list of cameras exists

Filter out the front camera if exists.

guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front })
.first as? AVCaptureDevice else {
   fatalError("Front camera not found")
}

The devices() method of AVCapture returns the list of cameras available. From that list of the camera, we’ll use the filter function in which we’ll check if the position is a camera in front or not. We can convert this to a function and use the front camera.

func checkCamera() {
   guard let frontCamera = AVCaptureDevice.devices().filter({ $0.position == .front })
   .first as? AVCaptureDevice else {
      fatalError("Front camera not found")
   }
}

Note − This cannot be run on a simulator as a simulator does not have any camera.

Updated on: 30-Jul-2019

804 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements