使用swift访问前置摄像头?

时间:2016-06-17 19:13:16

标签: ios swift ios-camera front-camera

我已经完成了一些搜索,大部分答案都在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
    }

后置摄像头是默认设置,但我没有看到如何直接访问前置摄像头以让人们来回交换。

2 个答案:

答案 0 :(得分:3)

您当前无效的 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
    }
}

答案 1 :(得分:0)

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 })
}