Swiftaccnt Swiftaccnt - 4 months ago 16x
Swift Question

Accessing front Camera with swift?

I've done some searching and most answers are either in Obj-C or not applicable to this code.

I'm using this guide : http://drivecurrent.com/devops/using-swift-and-avfoundation-to-create-a-custom-camera-view-for-an-ios-app/

and I've got this code from it:


captureSession = AVCaptureSession()
captureSession!.sessionPreset = AVCaptureSessionPresetPhoto

let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let frontCamera = ????

var error: NSError?
var input: AVCaptureDeviceInput!
do {
input = try AVCaptureDeviceInput(device: backCamera)
} catch let error1 as NSError {
error = error1
input = nil

The back camera is the default but I'm not seeing how to straight up access the front camera in order to let people swap back and forth.


Your currently void frontCamera has a pretty similar behavior to your backCamera one. You need to use devicesWithMediaType(_ mediaType: String!) that allows to store in an array all the devices capable of capturing data of type AVMediaTypeVideo.

I wouldn't recommend to call that variable frontCamera since you're going to have stored an array of 'devices' but that's the code implementation

let frontCamera = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
var captureDevice:AVCaptureDevice

for element in frontCamera{
    let element = element as! AVCaptureDevice
    if element.position == AVCaptureDevicePosition.Front {           
        captureDevice = element