iosswiftios-camerafront-camera

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:

     super.viewWillAppear(animated)

    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.


Solution

  • 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.

    let captureDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
    var frontCamera: AVCaptureDevice
    
    for device in captureDevices {
        let device = element as! AVCaptureDevice
        if device.position == AVCaptureDevicePosition.Front {           
            frontCamera = device
            break
        }
    }