lundi 20 juin 2016

Switching Camera causes AVCaptureSession to crash

I am attempting to include a switch camera button into my AVCaptureSession, however when I click n the switch camera button my camera view freezes and does not unfreeze. No errors occur, here is the code below

@IBAction func switchCamera(sender: AnyObject) {
    if Camera == true {Camera == false
        vwStartStopRecording.layer.cornerRadius = self.vwStartStopRecording.frame.size.width / 2
        vwStartStopRecording.clipsToBounds = true

        lpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action(_:)))


        lpgr!.minimumPressDuration = 0.75

        vwStartStopRecording.addGestureRecognizer(lpgr!)
        beginSession()
}
        else if Camera == false{Camera == true
        vwStartStopRecording.layer.cornerRadius = self.vwStartStopRecording.frame.size.width / 2
        vwStartStopRecording.clipsToBounds = true

        lpgr = UILongPressGestureRecognizer(target: self, action: #selector(self.action(_:)))


        lpgr!.minimumPressDuration = 0.75

        vwStartStopRecording.addGestureRecognizer(lpgr!)
        beginSession()
}else
    {print("error switching Camera")}

}
var Camera : Bool = true
//MARK: - BEGIN SESSION
func beginSession() {
    captureSession = AVCaptureSession()
    captureSession?.sessionPreset = AVCaptureSessionPresetMedium

    let frontCamera = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
        .map { $0 as! AVCaptureDevice }
        .filter { $0.position == .Front}
        .first!
    let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    var input : AVCaptureDeviceInput?
    let _ : NSError?
    do {
        if Camera == true {
            input = try AVCaptureDeviceInput(device: backCamera)
        }else if Camera == false {
            input = try AVCaptureDeviceInput(device: frontCamera)
        }else{
            input = try AVCaptureDeviceInput(device: backCamera)
        }
    } catch let error as NSError? {
        print(error)
        return//Stop rest of code
    }
    if (captureSession?.canAddInput(input))!{
        captureSession?.addInput(input)

        videoOutput = AVCaptureMovieFileOutput()
        //videoOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecKey]

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

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

}

Aucun commentaire:

Enregistrer un commentaire