The problem is that you are setting the camera source.
You set it to viewDidAppear, which is called only when the view appears on the device. This is when you go to this view controller from another or close the presented view controller that is represented by this.
My suggestion was to move the camera select code to its own function, which is called both viewDidLoad and whenever the changeCamera action is called.
@IBAction func changeCamera(sender: AnObject?) { camera = !camera reloadCamera() } func viewDidAppear(animated: Bool) { // normal code reloadCamera() } func reloadCamera() { // camera loading code captureSession = AVCaptureSession() captureSession!.sessionPreset = AVCaptureSessionPresetPhoto var captureDevice:AVCaptureDevice! = nil // var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) if (camera == false) { let videoDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in videoDevices{ let device = device as AVCaptureDevice if device.position == AVCaptureDevicePosition.Front { captureDevice = device break } } } else { var captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) } var error: NSError? var input = AVCaptureDeviceInput(device: captureDevice, error: &error) if error == nil && captureSession!.canAddInput(input) { captureSession!.addInput(input) stillImageOutput = AVCaptureStillImageOutput() stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] if captureSession!.canAddOutput(stillImageOutput) { captureSession!.addOutput(stillImageOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait previewView.layer.addSublayer(previewLayer) captureSession!.startRunning() } }
In addition, an additional improvement would be to use a custom enumeration to store which camera is currently in use, rather than a logical one. This means that you can add to it later if you had some third camera. It will look like this:
enum CameraType { case front case back } var camera = CameraType.back
Hope this helps, apologizing for excluding all code examples currently on the iPad, but I will update when I get to the computer.
Update
Before changing the camera, make sure that you delete the previous preview layer.
func reloadCamera() { captureSession?.stopRunning() previewLayer?.removeFromSuperlayer()
This should fix the camera freeze problem.
Elliott minns
source share