这似乎可以将相机从后面切换到前面,但我正在尝试提出一个’if’语句,以便我也可以将其切换回来.任何想法或建议? @IBAction func didTouchSwitchButton(sender: UIButton) { let camera = getDevice(.Fron
@IBAction func didTouchSwitchButton(sender: UIButton) { let camera = getDevice(.Front) let cameraBack = getDevice(.Back) do { input = try AVCaptureDeviceInput(device: camera) } catch let error as NSError { print(error) input = nil } if(captureSession?.canAddInput(input) == true){ captureSession?.addInput(input) stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if(captureSession?.canAddOutput(stillImageOutput) == true){ captureSession?.addOutput(stillImageOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer?.frame = cameraView.bounds cameraView.layer.addSublayer(previewLayer!) captureSession?.startRunning() } }
}
func switchCamera(_ sender: UIButton) { if let session = AVCaptureSession() { let currentCameraInput: AVCaptureInput = session.inputs[0] session.removeInput(currentCameraInput) var newCamera: AVCaptureDevice newCamera = AVCaptureDevice.default(for: AVMediaType.video)! if (currentCameraInput as! AVCaptureDeviceInput).device.position == .back { UIView.transition(with: self.cameraView, duration: 0.5, options: .transitionFlipFromLeft, animations: { newCamera = self.cameraWithPosition(.front)! }, completion: nil) } else { UIView.transition(with: self.cameraView, duration: 0.5, options: .transitionFlipFromRight, animations: { newCamera = self.cameraWithPosition(.back)! }, completion: nil) } do { try self.captureSession?.addInput(AVCaptureDeviceInput(device: newCamera)) } catch { print("error: \(error.localizedDescription)") } } } func cameraWithPosition(_ position: AVCaptureDevice.Position) -> AVCaptureDevice? { let deviceDescoverySession = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified) for device in deviceDescoverySession.devices { if device.position == position { return device } } return nil }