双击时如何切换到前置摄像头(SWIFT)

时间:2015-08-31 02:36:44

标签: ios iphone swift camera tap

起初我想为我的近似英语道歉。

我使用swift工作的Iphone项目。

在我的项目中,我有3个视图,其中一个我放了一个摄像头视图(后置摄像头),就像Snapchat菜单一样。当我双击时,我希望它切换到前置摄像头。

我在我的代码中添加了一个Tap手势识别器,但我不知道如何在其中初始化我的前置摄像头。

这是完整的代码。 如果您需要更多信息告诉我!谢谢。

    import UIKit
    import AVFoundation


    class View2: UIViewController,  UIImagePickerControllerDelegate, UINavigationControllerDelegate{

var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?


@IBAction func DoubleTap(sender: UITapGestureRecognizer) {


}


@IBOutlet var cameraView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.






}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    previewLayer?.frame = cameraView.bounds
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    captureSession = AVCaptureSession()
    captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080





//  Déclaration Caméra frontale








    let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    var error : NSError?
    var input: AVCaptureDeviceInput!
    do {
        input = try AVCaptureDeviceInput(device: backCamera)
    } catch let error1 as NSError {
        error = error1
        input = nil
    }

    if (error == nil && captureSession?.canAddInput(input) != nil){

        captureSession?.addInput(input)

        stillImageOutput = AVCaptureStillImageOutput()
        stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]

        if (captureSession?.canAddOutput(stillImageOutput) != nil){
            captureSession?.addOutput(stillImageOutput)

            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
            previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
            cameraView.layer.addSublayer(previewLayer!)
            captureSession?.startRunning()


        }


    }


}

1 个答案:

答案 0 :(得分:0)

可能是这个帮助

- (AVCaptureDevice *)showFrontCamera {
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if ([device position] == AVCaptureDevicePositionFront) {
            return device;
        }
    }
    return nil;
}

这是将返回前摄像头视图的功能。双击时调用此函数切换

AVCaptureDevice *device = [self showFrontCamera];

我在Objective-c中有代码,可能您可以根据需要将其转换为swift。