使用 swift 访问前置摄像头?

Accessing front Camera with swift?

我进行了一些搜索,大多数答案要么在 Obj-C 中,要么不适用于此代码。

我正在使用这个指南:http://drivecurrent.com/devops/using-swift-and-avfoundation-to-create-a-custom-camera-view-for-an-ios-app/

我从中得到了这段代码:

     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
    }

后置摄像头是默认设置,但我不知道如何直接向上访问前置摄像头以便让人们来回切换。

您当前的 void frontCamera 与您的 backCamera 具有非常相似的行为。您需要使用 devicesWithMediaType(_ mediaType: String!) 允许在数组中存储所有能够捕获 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
    }
}
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 })
}