如何在Swift中获得前置摄像头? [英] How to get the front camera in Swift?

查看:824
本文介绍了如何在Swift中获得前置摄像头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用实时视图获取前置摄像头。我能够使用后置摄像头:

I am trying to get the front camera with live view. I am able to get the back camera using:

var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

但我似乎无法找到如何获得前置摄像头。如何更改上面的代码才能使用前置摄像头?

But I can't seem to find how to get the front camera. How can I change the code above to use the front camera?

推荐答案

以下是我的一个项目的工作示例,以获取前置摄像头。这是目标-c但经过验证可以很容易地转换为swift。

Here is a working example from one of my projects to get the front camera. This is in objective-c but proven to work and easy enough to convert to swift.

NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *captureDevice = nil;

for (AVCaptureDevice *device in videoDevices){

    if (device.position == AVCaptureDevicePositionFront){

        captureDevice = device;
        break;
    }
}

在Swift 3.2 +中:

And in Swift 3.2+:

if let videoDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
    var captureDevice: AVCaptureDevice
    for device in videoDevices {
        if let device = device as? AVCaptureDevice {
            if device.position == AVCaptureDevicePosition.front {
                captureDevice = device
                break
            }
        }
    }
}

这篇关于如何在Swift中获得前置摄像头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆