0

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.

comrade
  • 4,590
  • 5
  • 33
  • 48
Barkley
  • 6,063
  • 3
  • 18
  • 25
  • 1
    You might want to check out this question - http://stackoverflow.com/questions/29155623/how-to-get-the-front-camera-in-swift – Roy Jun 17 '16 at 19:24
  • you can use the simple class which can manage the camera session -> https://github.com/maryamfekri/MFCameraManager – Maryam Fekri Feb 07 '17 at 11:10

2 Answers2

3

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
    }
}
1
func FromCamera() {
    let imagepicker = UIImagePickerController()
    imagepicker.delegate = self
    imagepicker.allowsEditing = true
    imagepicker.sourceType = UIImagePickerController.isSourceTypeAvailable(.Camera) ? .Camera : .PhotoLibrary
    imagepicker.cameraDevice = UIImagePickerController.isCameraDeviceAvailable(.Front) ? .Front : .Rear
    self.presentViewController(imagepicker, animated: true, completion: { _ in })
}
  • Not sure why this answer is not accepted since it provide complete functionality to capture using front camera. – iBug Jul 01 '22 at 08:27