bao bao -4 years ago 70
iOS Question

Can't use front camera in Swift

I want to build front camera, but couldn't build front camera in Swift even I could build back camera.

When I only change "back" to "front", camera didn't work...

How can I use front camera?

var captureSesssion: AVCaptureSession!
var stillImageOutput: AVCapturePhotoOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
var captureDevice : AVCaptureDevice!

override func viewDidLoad() {
super.viewDidLoad()

captureSesssion = AVCaptureSession()
stillImageOutput = AVCapturePhotoOutput()

captureSesssion.sessionPreset = AVCaptureSessionPreset1920x1080

captureDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front)
//When change "front" to "back", camera is built.

do {
let input = try AVCaptureDeviceInput(device: captureDevice)

if (captureSesssion.canAddInput(input)) {
captureSesssion.addInput(input)

if (captureSesssion.canAddOutput(stillImageOutput)) {
captureSesssion.addOutput(stillImageOutput)
captureSesssion.startRunning()

previewLayer = AVCaptureVideoPreviewLayer(session: captureSesssion)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait

self.view.layer.addSublayer(previewLayer!)

previewLayer?.position = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
previewLayer?.bounds = self.view.frame
}
}
}
catch {
print(error)
}

Answer Source

The front camera for iPhone 7 and iPhone 7 Plus can record 1080p but on older models it can only record 720p. Thus, you just need to change the session preset, i.e.:

captureSesssion.sessionPreset = AVCaptureSessionPreset1280x720
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download